Squares of a Sorted Array
Squares of a Sorted Array is LeetCode 977 (Easy). You get an integer array nums sorted in non-decreasing order, possibly with negative numbers.
- Return a new array holding the square of every number, also sorted in non-decreasing order.
- The follow-up asks for O(n) time, which rules out squaring and then sorting.
- 1 <= nums.length <= 10⁴
- -10⁴ <= nums[i] <= 10⁴
- nums is sorted in non-decreasing order.
Intuition
Squaring folds the number line at zero: −7 and 7 both become 49. In a sorted array, the numbers furthest from zero sit at the two ends, and the distance to zero shrinks as you walk inward from either side.
So the smallest square can be anywhere in the middle, but the largest square is always at one of the two ends. Compare the two ends, write the bigger square into the last empty slot of the result, and step that end inward. What is left is the same problem, one number shorter, so repeating this fills the result from the back, already in order.
A sorted array whose order gets scrambled in a predictable way (here, folded at zero) can often be rebuilt with two pointers walking in from the ends, the same move as merging two sorted lists.
Approach
Before reading on, decide where in nums the largest square can sit, and where the smallest one can. Then decide which end of the result array you can fill with certainty first.
Point at both ends and at the last slot
Create res with the same length as nums. Put l at index 0, r at the last index, and walk a write index w from the last slot down to 0. Slot w is always the biggest square still missing.
Write the bigger end's square
Compare abs(nums[l]) with abs(nums[r]) and put the square of the larger one in res[w]. Comparing absolute values (or squares) matters: the sign says nothing about the size of the square.
Move the end you used
If the left end won, move l right; otherwise move r left. The number just placed is done, and the other end is still a candidate for the next slot.
Why the result comes out sorted
Each slot gets the largest square among the numbers not yet placed, and slots are filled from the back. So every slot holds a value no bigger than the one after it, with no sorting step at all.
Code in Python, C++ and Java
Common pitfalls
Comparing the numbers instead of their sizes
if nums[l] > nums[r]:
if abs(nums[l]) > abs(nums[r]):
In a sorted array the left number is never bigger than the right one, so this always takes the right end. For [-7, 3] it writes 9 into the last slot and 49 before it, returning [49, 9].
Filling the result from the front
res[w] = min(nums[l] ** 2, nums[r] ** 2) # w = 0, 1, 2 …
res[w] = max(nums[l] ** 2, nums[r] ** 2) # w = n-1, n-2 …
The ends hold the largest squares, not the smallest. For [-4, -1, 0, 3, 10] the ends square to 16 and 100, but the smallest square, 0, is in the middle, so the first slot gets 16 instead of 0.
Stopping a while loop one number early
while l < r:
while l <= r:
When the two pointers meet, one number is still unplaced. With l < r, the input [5] never enters the loop and returns [0] instead of [25]. Looping over the write index, as in the code above, avoids the question.
Edge cases
[-5, -4, -3]The left end is always further from zero, so it wins every round and the result is the squares in reverse: [9, 16, 25].
[-3, 3]Both ends square to 9. Either may go first; the code takes the right one, and the result [9, 9] is the same.
Complexity
Squares of a Sorted Array FAQ
Is squaring everything and sorting good enough?
It is correct and short, but O(n log n). It is a fine first answer; the follow-up then asks for O(n), which is the two-pointer version on this page.
Can the squares be written back into nums itself?
Not safely with this method. The pointers still need to read numbers at both ends while the back of the array is being written, so writing into nums would overwrite a number before it is placed.
Can I start from zero and spread outward instead?
Yes. Find the first non-negative number, then merge leftward and rightward like two sorted lists, smallest square first. It is also O(n), but needs a search for the split point and more boundary checks.