Squares of a Sorted Array
Return the squares of a sorted array in sorted order in O(n), filling the result from the largest end.
The problem
You get an integer array nums sorted in non-decreasing order, which may include negative numbers. Return a new array with the square of each number, also sorted in non-decreasing order. Try to do it in O(n) time instead of squaring and sorting.
Input nums = [-6, -2, 0, 3, 5]
Output [0, 4, 9, 25, 36]
Negative numbers turn into large squares, so -6 ends up last as 36.
Input nums = [-3, -3, 1]
Output [1, 9, 9]
Both -3s become 9, and the smallest square comes from the 1 at the right end.
How to spot the pattern
- The input is sorted, but squaring negative numbers scrambles the order.
- The biggest square is always at one of the two ends of the array.
The idea
After squaring, the largest value must come from one of the two ends: either the most negative number or the most positive one. So compare the squares at both ends, write the bigger one into the last free slot of the result, and move that pointer inward. Filling the result from the back means you never need to sort.
Brute force: Square every number and sort the squares, which takes O(n log n) time.
Step by step
- 1Create
resultof the same length, and setleft = 0andright = n - 1. - 2Fill
resultfrom the back: for eachposfrom n - 1 down to 0, compare the absolute values ofnums[left]andnums[right]. - 3Write the square of the bigger one into
result[pos]and move that pointer inward:leftforward orrightbackward. - 4Return
resultonce every slot is filled.
See the pattern move
The two pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [0] * n
left, right = 0, n - 1
for pos in range(n - 1, -1, -1): # fill from the largest end
if abs(nums[left]) > abs(nums[right]):
result[pos] = nums[left] * nums[left]
left += 1
else:
result[pos] = nums[right] * nums[right]
right -= 1
return resultComplexity
Time
O(n)
Space
O(1)
One pass with two pointers. Apart from the result array, which you have to return anyway, only three indices are stored.
Watch out for
- Filling the result from the front: the smallest square can sit anywhere in the middle, while the largest one is always at an end.
- Comparing the numbers instead of their absolute values: -6 is smaller than 5, but its square is bigger.
Follow-up questions
Is there another way to merge in O(n)?
Find the first non-negative number (by scanning or binary search), then merge outward with one pointer moving left through the negatives and one moving right through the rest, smallest square first. It is the merge step of merge sort.
What if you had to apply a * x^2 + b * x + c instead of squaring?
For a parabola that opens upward (a > 0), the largest values are still at the two ends, so fill from the back the same way. If it opens downward, the smallest values are at the ends, so fill from the front instead.
In Hinglish
Sabse bada square hamesha kisi ek end par hota hai; dono ends compare karo aur result ko peeche se bharo.