15% off all plans & roadmaps Use code

See plans

Squares of a Sorted Array

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^4
  • nums is 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create an output array with the same length as A.
  2. Loop over A and store each value multiplied by itself in the output.
  3. Sort the output in non-decreasing order.
  4. 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

TimeO(n log n)
SpaceO(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 squares

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 infographic

Solution 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

  1. Allocate result of length n. Set left = 0, right = n - 1, and pos = n - 1.
  2. While left is at most right, compare abs(A[left]) with abs(A[right]).
  3. If the left magnitude is larger, write A[left] squared at result[pos] and increase left.
  4. Otherwise write A[right] squared at result[pos] and decrease right.
  5. Decrease pos by one and repeat.
  6. Return result.

Dry run

Stepleft (value)right (value)ComparisonWriteresult after step
init0 (-10000)4 (10000)nonenone[?, ?, ?, ?, ?]
10 (-10000)4 (10000)10000 vs 10000, tie goes right100000000 at pos 4, right becomes 3[?, ?, ?, ?, 100000000]
20 (-10000)3 (5000)10000 > 5000, left100000000 at pos 3, left becomes 1[?, ?, ?, 100000000, 100000000]
31 (-5000)3 (5000)5000 vs 5000, tie goes right25000000 at pos 2, right becomes 2[?, ?, 25000000, 100000000, 100000000]
41 (-5000)2 (0)5000 > 0, left25000000 at pos 1, left becomes 2[?, 25000000, 25000000, 100000000, 100000000]
52 (0)2 (0)0 vs 0, tie goes right0 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

TimeO(n)
SpaceO(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 result

Common mistakes

  • if A[left] > A[right] compares raw values. With [-10, 2] it picks 2 and writes 4 first. Compare abs(A[left]) with abs(A[right]) instead.
  • Filling result from index 0 upward. The ends hold the largest squares, so the front slot needs the smallest value, which sits in the middle. Fill from n - 1 downward.
  • while left < right stops one step early. When the pointers meet, one element is still unwritten. Use left <= 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 pos forward. 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

Practise it