Squares of a Sorted Array
1 approach, code in every language
Problem description
You receive an integer array already sorted in non-decreasing order. Produce a new array containing the square of every element, arranged from smallest to largest.
The challenge is that negative numbers can square into large values, so the largest squares live at the two ends of the input rather than in the middle.
Example 1
Input: nums = [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Squaring gives 16, 1, 0, 9, 100, which sorts into the shown result.
Example 2
Input: nums = [-7, -3, 2, 3, 11]
Output: [4, 9, 9, 49, 121]
The largest square, 121, comes from the rightmost value while 49 comes from the leftmost.
Constraints
1 ≤ nums.length ≤ 10^4-10^4 ≤ nums[i] ≤ 10^4nums is sorted in non-decreasing order
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Sorted Drift Energies is our own problem on the technique behind Squares of a Sorted Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free