Squares of a Sorted Array (LeetCode 977): Solution and Explanation

Easy
Array
Two Pointers
Sorting

You are given an integer array sorted in non-decreasing order, possibly containing negative numbers. Return a new array of the squares of each number, also sorted in non-decreasing order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The quickest solution to write is to square every element and sort the result. That is correct and takes O(n log n) time. It ignores the fact that the input is already sorted, though, and the follow-up asks whether you can do it in linear time.

The reason squaring breaks the order is the negative numbers. Squares grow with absolute value, and in a sorted array with negatives, the largest absolute values sit at both ends: the most negative number on the left and the most positive number on the right. The smallest absolute values are somewhere in the middle, near zero. So the array of absolute values goes down and then up, like a valley.

That shape tells you where the largest square must be: at one of the two ends. Put a pointer at each end and compare absolute values. Whichever is larger produces the largest remaining square, so write it into the last open slot of the result and move that pointer inward. Repeat, filling the result from right to left. Each step places one element in its final position, so the whole thing takes a single pass. You could also start in the middle and merge outward, but finding the split point adds work, and filling from the outside in avoids that.

Approach: Two pointers from both ends

  1. Allocate result of length n, and set left = 0 and right = n - 1.
  2. Loop i from n - 1 down to 0; this is the slot to fill next with the largest remaining square.
  3. If abs(nums[left]) > abs(nums[right]), write nums[left] ** 2 into result[i] and move left one step right.
  4. Otherwise write nums[right] ** 2 into result[i] and move right one step left.
  5. When the loop finishes, every slot is filled in ascending order, so return result.

Step-by-step example

nums = [-4, -1, 0, 3, 10]
  1. i = 4: compare |-4| and |10|. Ten is larger, so result[4] = 100 and right moves to index 3.
  2. i = 3: compare |-4| and |3|. Four is larger, so result[3] = 16 and left moves to index 1.
  3. i = 2: compare |-1| and |3|. Three is larger, so result[2] = 9 and right moves to index 2.
  4. i = 1: compare |-1| and |0|. One is larger, so result[1] = 1 and left moves to index 2.
  5. i = 0: both pointers are at index 2, the values tie, so result[0] = 0. The final array is [0, 1, 9, 16, 100].

Code: Python, Java, C++

1class Solution:
2    def sortedSquares(self, nums: List[int]) -> List[int]:
3        n = len(nums)
4        result = [0] * n
5        left, right = 0, n - 1
6        for i in range(n - 1, -1, -1):
7            if abs(nums[left]) > abs(nums[right]):
8                result[i] = nums[left] ** 2
9                left += 1
10            else:
11                result[i] = nums[right] ** 2
12                right -= 1
13        return result

Time and space complexity

Time

O(n)

Each loop iteration places exactly one square and moves exactly one pointer, so there are n iterations of constant work.

Space

O(n)

The result array has n elements. If the output does not count, the extra space is O(1), just the pointers.

Other approaches

Square then sort (time O(n log n), space O(n) or O(log n) depending on the sort)

Square every element in place and call the built-in sort. It is the shortest code and perfectly acceptable for small inputs, but it does not use the sorted input and costs a logarithmic factor.

Find the split and merge outward (time O(n), space O(n))

Binary search for the first non-negative element, then merge the negative part (read right to left) with the non-negative part (read left to right) like merge sort. It also runs in linear time but requires extra boundary handling.

Common mistakes

  • Filling the result from the front. The two ends hold the largest absolute values, not the smallest, so the smallest square is in the middle and cannot be found by comparing the ends.
  • Comparing nums[left] and nums[right] without absolute values. A negative left element always looks smaller even when its square is larger.
  • Using left < right as the loop condition. That stops one element early and leaves a slot unfilled; looping over all n output positions avoids the problem.
  • Writing left += 1 in both branches by copy and paste. Only the pointer whose element was just placed should move, otherwise one end is skipped and a square is lost.

Frequently asked questions

Can Squares of a Sorted Array be solved in O(n)?

Yes. Because the largest squares are always at the two ends of the sorted input, two pointers can fill the output from largest to smallest in one pass.

Why fill the result from the end instead of the beginning?

The ends of the input give you the largest absolute values, so they tell you the largest square with certainty. The smallest square is near zero in the middle, which the end pointers cannot see directly.

What if the array has no negative numbers?

The algorithm still works. The right pointer always wins the comparison, so it simply writes the squares from right to left in their original order.