LeetCode #977 Easy

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.
Constraints
  • 1 <= nums.length <= 10⁴
  • -10⁴ <= nums[i] <= 10⁴
  • nums is sorted in non-decreasing order.
two-pointersarraysorting
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sortedSquares(self, nums: list[int]) -> list[int]:
▶3 n = len(nums)
▶4 res = [0] * n
▶5 l, r = 0, n - 1
▶6 for w in range(n - 1, -1, -1):
▶7 if abs(nums[l]) > abs(nums[r]):
▶8 res[w] = nums[l] * nums[l]
▶9 l += 1
▶10 else:
▶11 res[w] = nums[r] * nums[r]
▶12 r -= 1
▶13 return res
numsresult-4Lsq 16-10310Rsq 10001234biggest square is at an end
L0
R4
next slot4
The numbers furthest from zero sit at the two ends, so the largest square is under L or R. The result is filled from its last slot, 4, backwards.
numsresult-4Lsq 16-103Rsq 91001231004right 100 beats 16 → slot 4
left sq16
right sq100
result[_, _, _, _, 100]
The ends square to 16 (left) and 100 (right). The right one is bigger, and no number between them can beat it, so 100 is the largest square left. It goes into slot 4 and R steps inward.
numsresult-4-1Lsq 103Rsq 9100121631004left 16 beats 9 → slot 3
left sq16
right sq9
result[_, _, _, 16, 100]
The ends square to 16 (left) and 9 (right). The left one is bigger, and no number between them can beat it, so 16 is the largest square left. It goes into slot 3 and L steps inward.
numsresult-4-1Lsq 10Rsq 031001921631004right 9 beats 1 → slot 2
left sq1
right sq9
result[_, _, 9, 16, 100]
The ends square to 1 (left) and 9 (right). The right one is bigger, and no number between them can beat it, so 9 is the largest square left. It goes into slot 2 and R steps inward.
numsresult-4-10L Rsq 0310011921631004left 1 beats 0 → slot 1
left sq1
right sq0
result[_, 1, 9, 16, 100]
The ends square to 1 (left) and 0 (right). The left one is bigger, and no number between them can beat it, so 1 is the largest square left. It goes into slot 1 and L steps inward.
numsresult-4-103100011921631004last number 0 → slot 0
left sq0
right sq0
result[0, 1, 9, 16, 100]
L and R meet on 0, the only number left, so its square 0 fills the last empty slot, 0.
numsresult-4-103100011921631004all 5 slots filled → sorted
result[0, 1, 9, 16, 100]
Every slot got the largest square that was still unplaced, filling from the back, so the result [0, 1, 9, 16, 100] is already in order. No sort was needed.
05

Common pitfalls

Comparing the numbers instead of their sizes

✗ Wrong
if nums[l] > nums[r]:
✓ Right
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

✗ Wrong
res[w] = min(nums[l] ** 2, nums[r] ** 2)  # w = 0, 1, 2 …
✓ Right
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

✗ Wrong
while l < r:
✓ Right
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.

06

Edge cases

All numbers negative, like [-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].

Equal sizes, like [-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.

07

Complexity

Time
O(n)
Space
O(1) extra
Each round writes one slot and moves one pointer, so there are exactly n rounds. Apart from the output array, only three indexes are stored.
08

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.