Squares of a Sorted Array solution explained
To return the squares of a sorted array in sorted order without sorting again, put one pointer at each end of the input. The largest square always comes from whichever end has the larger absolute value, so write that square into the last free slot of the output and move that pointer inward. One pass gives O(n) time and O(n) space for the output, instead of O(n log n) for squaring and sorting.
By Evin JohnPublished 7 min read
The problem, in plain terms
You receive a list of integers sorted in non-decreasing order. Some may be negative. Produce a new list that contains the square of every element, also in non-decreasing order. The catch is that squaring a negative number makes it positive, so the left end of the input can hold some of the largest squares.
input: [-6, -2, -1, 0, 3, 4]
squares: [36, 4, 1, 0, 9, 16] not sorted
answer: [ 0, 1, 4, 9, 16, 36]
lo -> -6, hi -> 4 |-6| > |4| write 36 at index 5, lo moves right
lo -> -2, hi -> 4 |-2| < |4| write 16 at index 4, hi moves left
lo -> -2, hi -> 3 |-2| < |3| write 9 at index 3, hi moves left
lo -> -2, hi -> 0 |-2| > |0| write 4 at index 2, lo moves right
lo -> -1, hi -> 0 |-1| > |0| write 1 at index 1, lo moves right
lo -> 0, hi -> 0 same cell write 0 at index 0Before writing code, confirm whether the input can be empty, whether values can be large enough that a square overflows the integer type you are using, and whether a new array is fine or the answer must overwrite the input. A new array is the usual expectation.
Why it gets asked
It is a short problem with a clear before-and-after. Most candidates find the O(n log n) answer immediately, and the interviewer then asks whether the sorted input can help. The good answer comes from one observation about where large absolute values live, which makes it a quick test of whether you look at structure in the input instead of reaching for a library call.
The slower starting point: square, then sort
Square every element and sort the result. That is correct and takes O(n log n) time. There is one trap in JavaScript: calling sort() with no comparator converts the numbers to strings, so 16 would land before 4 and 100 before 25. Always pass (a, b) => a - b. It is a good small detail to mention, because it shows you know the language and not only the algorithm.
A middle route finds the boundary between negative and non-negative values with a binary search, then merges outward from that boundary like two sorted lists. That is O(n) too, but it needs extra care at the boundary and is harder to get right under pressure than the version below.
The optimal approach: converge from both ends
Allocate an output of the same length. Keep lo at the first index and hi at the last. For each output position from the last down to the first, compare the absolute values at lo and hi. Write the square of the larger one and move that pointer one step inward. The outermost values have the largest magnitudes, so the output fills from largest square to smallest and ends up sorted without ever being sorted.
def sorted_squares(nums):
n = len(nums)
out = [0] * n
lo, hi = 0, n - 1
for k in range(n - 1, -1, -1): # fill from the largest square down
if abs(nums[lo]) > abs(nums[hi]):
out[k] = nums[lo] * nums[lo]
lo += 1
else:
out[k] = nums[hi] * nums[hi]
hi -= 1
return outfunction sortedSquares(nums) {
const out = new Array(nums.length);
let lo = 0, hi = nums.length - 1;
for (let k = nums.length - 1; k >= 0; k--) {
const left = nums[lo] * nums[lo], right = nums[hi] * nums[hi];
if (left > right) { out[k] = left; lo++; }
else { out[k] = right; hi--; }
}
return out;
}On ties either side can go first, since both squares are equal. The loop runs exactly n times, and when lo and hi meet on the final element, whichever branch runs writes that element's square into position 0. Comparing squares instead of absolute values, as the JavaScript version does, gives the same result and avoids a function call, at the cost of computing a square that may be thrown away.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Square, then sort | O(n log n) | O(n) output, plus the sort's own space |
| Binary search for zero, then merge outward | O(n) | O(n) output |
| Two pointers from both ends | O(n) | O(n) output, O(1) besides it |
Any approach needs O(n) for the output, so interviewers usually mean the space beyond the output when they ask about memory. The two-pointer version uses only a few variables on top of it.
Edge cases to test
- All negative values, where the output is the input reversed and squared.
- All non-negative values, where the output is just the squares in the same order.
- Zeros in the middle, and repeated values such as -3 and 3 together.
- A single element, including a single negative one.
- An empty list, which should return an empty list without indexing anything.
- Large magnitudes, where the square may overflow a fixed-width integer.
Mistakes to avoid
- Filling the output from the front. The smallest square can sit anywhere in the input, often in the middle, so there is no safe way to fill the front first.
- Comparing nums[lo] and nums[hi] without absolute values, which treats -6 as smaller than 4.
- Using JavaScript's default sort in the brute-force version, which compares as strings.
- Overflow in languages with fixed-width integers: a 32-bit int cannot hold the square of values above about 46,340, so use a 64-bit type when values can be that large. In JavaScript, squares stay exact only up to 2^53, which means magnitudes up to about 94.9 million.
- Stopping when lo equals hi instead of when the output is full, which leaves the last slot unwritten.
How to explain it out loud
Fictional example
- Candidate
- The quick answer is square everything and sort, which is n log n. But the input is already sorted, so I'd like to use that.
- Candidate
- The biggest square has to come from one of the two ends, because those have the largest absolute values. So I'll fill the output from the back, comparing the two ends and taking the bigger one each time.
- Candidate
- Each step places one value and moves one pointer, so it's a single pass. Space is just the output array.
Variations
- Return cubes instead of squares: cubing keeps the sign, so the input order is already the answer.
- Apply a general quadratic a·x² + b·x + c to a sorted list: the same two-pointer fill works, from the back when a is positive and from the front when a is negative.
- Return the k largest squares only: run the same loop for k steps.
- Count distinct squares: the same pointers, skipping repeated absolute values as you go.
Related problems
The fill-from-the-back trick is the same one used by Merge Sorted Array, where the largest remaining value of two lists goes into the last free slot. Two pointers inside one sorted array also appear in Remove Duplicates from Sorted Array, where both move in the same direction.
How Natively helps you rehearse
This problem rewards a calm explanation of one observation. When you practice on your Mac or Windows machine, Natively can pick up the problem from a screenshot, suggest edge cases like an all-negative input, and give you a transcript of your answer so you can hear whether you jumped straight to sorting. More about AI help for coding interview prep.
Questions people ask
How do you solve Squares of a Sorted Array in O(n)?
Place one pointer at each end. The larger absolute value of the two gives the largest remaining square, so write it into the last free output slot and move that pointer inward until the output is full.
Why not just square and sort?
That works and is a fine first answer, but it costs O(n log n). The input is already sorted by value, which means the largest absolute values sit at the two ends, and using that gives a linear pass.
Why fill the output from the back?
The two ends of the input always hold the largest magnitudes, so the largest square is known at every step. The smallest square can be anywhere, so the front cannot be filled first.
What is the space complexity?
O(n) for the output array, which any approach needs, and O(1) beyond it for the two pointers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
