Squares of a Sorted Array (LeetCode 977): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Allocate
resultof lengthn, and setleft = 0andright = n - 1. - Loop
ifromn - 1down to 0; this is the slot to fill next with the largest remaining square. - If
abs(nums[left]) > abs(nums[right]), writenums[left] ** 2intoresult[i]and moveleftone step right. - Otherwise write
nums[right] ** 2intoresult[i]and moverightone step left. - When the loop finishes, every slot is filled in ascending order, so return
result.
Step-by-step example
nums = [-4, -1, 0, 3, 10]
i = 4: compare |-4| and |10|. Ten is larger, soresult[4] = 100andrightmoves to index 3.i = 3: compare |-4| and |3|. Four is larger, soresult[3] = 16andleftmoves to index 1.i = 2: compare |-1| and |3|. Three is larger, soresult[2] = 9andrightmoves to index 2.i = 1: compare |-1| and |0|. One is larger, soresult[1] = 1andleftmoves to index 2.i = 0: both pointers are at index 2, the values tie, soresult[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 result1class Solution {
2 public int[] sortedSquares(int[] nums) {
3 int n = nums.length;
4 int[] result = new int[n];
5 int left = 0, right = n - 1;
6 for (int i = n - 1; i >= 0; i--) {
7 if (Math.abs(nums[left]) > Math.abs(nums[right])) {
8 result[i] = nums[left] * nums[left];
9 left++;
10 } else {
11 result[i] = nums[right] * nums[right];
12 right--;
13 }
14 }
15 return result;
16 }
17}1class Solution {
2public:
3 vector<int> sortedSquares(vector<int>& nums) {
4 int n = nums.size();
5 vector<int> result(n);
6 int left = 0, right = n - 1;
7 for (int i = n - 1; i >= 0; i--) {
8 if (abs(nums[left]) > abs(nums[right])) {
9 result[i] = nums[left] * nums[left];
10 left++;
11 } else {
12 result[i] = nums[right] * nums[right];
13 right--;
14 }
15 }
16 return result;
17 }
18};Time and space complexity
O(n)
Each loop iteration places exactly one square and moves exactly one pointer, so there are n iterations of constant work.
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]andnums[right]without absolute values. A negative left element always looks smaller even when its square is larger. - Using
left < rightas the loop condition. That stops one element early and leaves a slot unfilled; looping over all n output positions avoids the problem. - Writing
left += 1in 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.