15% off all plans & roadmaps Use code
See plansSquares of a Sorted Array
- LeetCode 977
- Easy
- Two Pointers
- Converging (Sorted Array Target Sum)
Updated
TL;DR: Given a sorted array that may contain negative numbers, return the squares of its values in sorted order. The key idea is that the largest square always sits at one of the two ends, so you fill the result from the back using two converging pointers.
Problem
You get an integer array nums sorted in non-decreasing order. Square each value, then return the squared values as a new array that is also sorted in non-decreasing order.
Example 1
Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: Squaring the values gives [16,1,0,9,100]. Sorting that list gives [0,1,9,16,100].
Example 2
Input: nums = [-7,-3,2,3,11] Output: [4,9,9,49,121]
Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i] <= 10^4numsis sorted in non-decreasing order.
Constraints that matter
- n up to 10^4 is small enough that O(n log n) passes, so the interview question is really about whether you can beat the sort.
- Values lie between -10^4 and 10^4, so each square is at most 10^8. That fits in a 32-bit int, and you do not need a long.
- The array is already sorted. A solution that ignores this order does redundant work, which rules out treating the input as unordered.
- The array can be all negative or all positive, so the algorithm must handle one side being empty without special cases.
Hints
Hint 1
Sorting by value is the wrong lens here.
Hint 2
Square every element into a new array, then sort that array.
Solution
Intuition
Sorting by value is the wrong lens here. The input is sorted, but squaring breaks that order. A large negative such as -10 squares to 100, while 3 squares to 9. The squares shrink toward the middle of the array and grow toward both ends.
Picture a row of posts, tallest at the two ends and shortest in the middle, with a shelf filled from its back. The left and right pointers are the two end posts, and each step moves the taller one onto the next back slot.
Notice where the biggest square lives. Its absolute value is the largest in the whole array, and that value is at one end. At any moment, only the two end candidates can be the largest remaining square.
This is the converging two pointers pattern. Put one pointer at each end, take the larger square, write it into the back of the result, and move the pointer that supplied it. Each step fixes one output slot, so the result comes out sorted without a sort step.
Worked example
Input: nums = [-10000, -5000, 0, 5000, 10000] Output: [0, 25000000, 25000000, 100000000, 100000000] Explanation: The two largest magnitudes sit at the ends, so the ends win first. The middle value 0 squares to the smallest result and lands at the front. Each square appears twice because the input has matching magnitudes on both sides of zero.
Approach 1: Brute force: square, then sort
Square every element into a new array, then sort that array. Squaring is cheap, but the squares are no longer in order, so the sort does all the ordering work. The sorted input order is never used, and that is the waste the next approach removes.
Steps
- Create an output array with the same length as
A. - Loop over
Aand store each value multiplied by itself in the output. - Sort the output in non-decreasing order.
- Return the output.
Dry run
Squaring [-10000, -5000, 0, 5000, 10000] gives [100000000, 25000000, 0, 25000000, 100000000]. The sort moves 0 to the front, then the two 25000000 values, then the two 100000000 values. The final output is [0, 25000000, 25000000, 100000000, 100000000], which matches the expected answer.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the length of A. The squaring loop does n steps. Sorting n values takes O(n log n) comparisons in the general case, and that cost dominates the loop. The output holds n values, so extra space is O(n). Sort workspace differs by language, from O(log n) for in-place quicksort to O(n) for Python's Timsort.
PythonTested in our runner
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
# Square every value, then let the sort put them in order
squares = [x * x for x in A]
squares.sort()
return squaresJavaTested in our runner
import java.util.*;
class Solution {
public int[] sortedSquares(int[] A) {
int[] result = new int[A.length];
for (int i = 0; i < A.length; i++) {
result[i] = A[i] * A[i];
}
Arrays.sort(result);
return result;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
vector<int> result;
for (int x : A) {
result.push_back(x * x);
}
sort(result.begin(), result.end());
return result;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @return {number[]}
*/
var sortedSquares = function(A) {
return A.map(x => x * x).sort((a, b) => a - b);
};GoTested in our runner
import "sort"
func sortedSquares(A []int) []int {
result := make([]int, len(A))
for i, x := range A {
result[i] = x * x
}
sort.Ints(result)
return result
}C#Tested in our runner
public class Solution {
public int[] sortedSquares(int[] A) {
int[] result = A.Select(x => x * x).ToArray();
Array.Sort(result);
return result;
}
}The Converging (Sorted Array Target Sum) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Converging (Sorted Array Target Sum)
Part of Two Pointers
Approach 2: Converging two pointers, filled from the backOptimalConverging (Sorted Array Target Sum)
The brute force sorts data whose order is already known, which wastes the input structure. The insight: the largest square is always at the left end or the right end, because only the ends hold the largest magnitudes. So fill the result from its last slot toward the first.
At each step, compare the absolute values at both ends. Square the larger one, write it at the current slot, and move the pointer that supplied it inward. Every step places the largest remaining square, so no sort is needed.
Why it is correct. The unplaced values always form the window between left and right. Since the array is sorted by value, the largest magnitude in that window sits at one of its two ends. Writing that square at the current back slot therefore never misplaces a larger value, so the output is sorted.
Steps
- Allocate
resultof length n. Setleft = 0,right = n - 1, andpos = n - 1. - While
leftis at mostright, compareabs(A[left])withabs(A[right]). - If the left magnitude is larger, write
A[left]squared atresult[pos]and increaseleft. - Otherwise write
A[right]squared atresult[pos]and decreaseright. - Decrease
posby one and repeat. - Return
result.
Dry run
| Step | left (value) | right (value) | Comparison | Write | result after step |
|---|---|---|---|---|---|
| init | 0 (-10000) | 4 (10000) | none | none | [?, ?, ?, ?, ?] |
| 1 | 0 (-10000) | 4 (10000) | 10000 vs 10000, tie goes right | 100000000 at pos 4, right becomes 3 | [?, ?, ?, ?, 100000000] |
| 2 | 0 (-10000) | 3 (5000) | 10000 > 5000, left | 100000000 at pos 3, left becomes 1 | [?, ?, ?, 100000000, 100000000] |
| 3 | 1 (-5000) | 3 (5000) | 5000 vs 5000, tie goes right | 25000000 at pos 2, right becomes 2 | [?, ?, 25000000, 100000000, 100000000] |
| 4 | 1 (-5000) | 2 (0) | 5000 > 0, left | 25000000 at pos 1, left becomes 2 | [?, 25000000, 25000000, 100000000, 100000000] |
| 5 | 2 (0) | 2 (0) | 0 vs 0, tie goes right | 0 at pos 0, right becomes 1 | [0, 25000000, 25000000, 100000000, 100000000] |
After step 5, left is 2 and right is 1, so the loop stops. The result matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) total, O(1) auxiliary |
Let n be the length of A. Each iteration moves either left up or right down, and the two pointers cross after at most n moves, so the loop runs at most n times. Each iteration does constant work: two absolute values, one multiply, and one write. The output array holds n values, so total space is O(n), while the pointers and pos use O(1) auxiliary space.
PythonTested in our runner
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
n = len(A)
result = [0] * n
left, right = 0, n - 1
pos = n - 1 # next slot to fill, from the largest down
while left <= right:
if abs(A[left]) > abs(A[right]):
result[pos] = A[left] * A[left]
left += 1
else:
result[pos] = A[right] * A[right]
right -= 1
pos -= 1
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] sortedSquares(int[] A) {
int n = A.length;
int[] result = new int[n];
int left = 0;
int right = n - 1;
int pos = n - 1; // next slot to fill, from the largest down
while (left <= right) {
if (Math.abs(A[left]) > Math.abs(A[right])) {
result[pos] = A[left] * A[left];
left++;
} else {
result[pos] = A[right] * A[right];
right--;
}
pos--;
}
return result;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int n = A.size();
vector<int> result(n);
int left = 0;
int right = n - 1;
int pos = n - 1; // next slot to fill, from the largest down
while (left <= right) {
if (abs(A[left]) > abs(A[right])) {
result[pos] = A[left] * A[left];
left++;
} else {
result[pos] = A[right] * A[right];
right--;
}
pos--;
}
return result;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @return {number[]}
*/
var sortedSquares = function(A) {
const n = A.length;
const result = new Array(n);
let left = 0;
let right = n - 1;
let pos = n - 1; // next slot to fill, from the largest down
while (left <= right) {
if (Math.abs(A[left]) > Math.abs(A[right])) {
result[pos] = A[left] * A[left];
left++;
} else {
result[pos] = A[right] * A[right];
right--;
}
pos--;
}
return result;
};GoTested in our runner
func sortedSquares(A []int) []int {
n := len(A)
result := make([]int, n)
left, right := 0, n-1
pos := n - 1 // next slot to fill, from the largest down
for left <= right {
l, r := A[left], A[right]
if l < 0 {
l = -l
}
if r < 0 {
r = -r
}
if l > r {
result[pos] = A[left] * A[left]
left++
} else {
result[pos] = A[right] * A[right]
right--
}
pos--
}
return result
}C#Tested in our runner
public class Solution {
public int[] sortedSquares(int[] A) {
int n = A.Length;
int[] result = new int[n];
int left = 0;
int right = n - 1;
int pos = n - 1; // next slot to fill, from the largest down
while (left <= right) {
if (Math.Abs(A[left]) > Math.Abs(A[right])) {
result[pos] = A[left] * A[left];
left++;
} else {
result[pos] = A[right] * A[right];
right--;
}
pos--;
}
return result;
}
}Common mistakes
if A[left] > A[right]compares raw values. With[-10, 2]it picks 2 and writes 4 first. Compareabs(A[left])withabs(A[right])instead.- Filling
resultfrom index 0 upward. The ends hold the largest squares, so the front slot needs the smallest value, which sits in the middle. Fill fromn - 1downward. while left < rightstops one step early. When the pointers meet, one element is still unwritten. Useleft <= right.- Moving both pointers in the same iteration. Only the pointer that supplied the chosen value should move, or you skip values.
- Forgetting to decrement
pos, or decrementing it in only one branch. Each iteration must write exactly one slot. - Storing squares in a 32-bit int is safe here only because
|nums[i]|is at most 10^4. A bound of 10^9 would overflow int in Java, C++, or C#, and you would need 64-bit values.
Edge cases
- Single element
[-3]returns[9]. The loop runs once and writes one slot. - All non-negative
[1, 2, 3]returns[1, 4, 9]. The right pointer does all the work. - All negative
[-5, -4, -1]returns[1, 16, 25]. The left pointer does all the work. - Equal magnitudes
[-2, 2]return[4, 4]. The tie branch writes one square and moves on, then the last slot fills. - Zero between negatives and positives
[-1, 0, 1]returns[0, 1, 1]. The zero lands at the front because it is the smallest square. - Maximum size with values at -10^4 and 10^4 returns squares of 10^8 at the back. That fits in a 32-bit int.
Follow-ups interviewers ask
- What if the result must be in non-increasing order?
- Fill the array from the front instead. Write the larger end square at index 0 and move
posforward. The time and space bounds stay the same. - What if the input is not sorted?
- The two-pointer argument depends on sorted order, so it no longer applies. Sorting the squares takes O(n log n) in general. Since the values lie in the range from -10^4 to 10^4, counting sort over that range runs in O(n + 10^4) time.
- Can you avoid the extra output array?
- Not in a clean way. The squares move to new positions, and the negatives at the front must shift, so writing in place needs more work than the two-pointer loop. The usual answer allocates the output and states that the extra space is O(n). The auxiliary space is O(1).
Squares of a Sorted Array FAQ
What is the time complexity of Squares of a Sorted Array?
The two-pointer solution runs in O(n) time because each iteration moves one pointer inward and the pointers cross after at most n moves. The sort-based solution runs in O(n log n) time because the sort dominates.
Why use converging two pointers for Squares of a Sorted Array?
The largest square always sits at one of the two ends, so only the two ends can be the next largest value. Converging pointers examine each value once and write the answer from the back, which keeps the output sorted without a sort.
Can Squares of a Sorted Array be solved in O(1) extra space?
Yes, if you count only auxiliary space. The pointers and the write index use constant memory. The output array still takes O(n), and that is the standard convention for this problem.
Why compare absolute values instead of the raw numbers?
A large negative number has a larger square than a smaller positive number. Comparing absolute values compares the squares directly, because squaring preserves the order of magnitudes.
Asked at
See which companies ask this — Pro
Related problems
- Merge Sorted Array · same technique: Converging (Sorted Array Target Sum)
- 3Sum · same technique: Converging (Sorted Array Target Sum)
- Container With Most Water · same technique: Converging (Sorted Array Target Sum)
- Two Sum II - Input Array Is Sorted · same technique: Converging (Sorted Array Target Sum)
- Two Sum · same pattern: Two Pointers
- Contains Duplicate · same pattern: Two Pointers
- Happy Number · same pattern: Two Pointers
- Valid Anagram · same pattern: Two Pointers
- Plus One · same pattern: Two Pointers
- Missing Number · same pattern: Two Pointers