Easy
Squares of a Sorted Array
- Time limit
- 1 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Two Pointers
Description
Description
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.
The input may contain negative numbers; squaring them produces positive values that can appear out of order, so the output must be re-sorted.
Examples
Example 1
- Input:
nums = [-4, -1, 0, 3, 10] - Output:
[0, 1, 9, 16, 100] - Explanation: The squares are
16, 1, 0, 9, 100; sorted, they become0, 1, 9, 16, 100.
Example 2
- Input:
nums = [-7, -3, 2, 3, 11] - Output:
[4, 9, 9, 49, 121]
Example 3
- Input:
nums = [1, 2, 3] - Output:
[1, 4, 9]
Expected Function Behavior
Implement sortedSquares(nums) and return the sorted array of squares.
Constraints
0 <= nums.length <= 100000-10000 <= nums[i] <= 10000numsis sorted in non-decreasing order.- Each squared value fits in a signed 32-bit integer.
Sample cases
3Sample 1
Input
nums = [-4,-1,0,3,10]
Expected output
[0,1,9,16,100]
Sample 2
Input
nums = [-7,-3,2,3,11]
Expected output
[4,9,9,49,121]
Skills and languages
Patterns
- Two Pointers
- Merging and Splitting Lists
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer