Squares of a Sorted Array

Easy

Topics
ArrayTwo PointersSorting

Given an array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.

Example 1

nums-4-10310
squares01916100
negative — squares in reverse order
Squaring breaks the sort order, because the largest square can come from either end. Comparing the two ends and filling the output from the back gives it in one linear pass, instead of squaring then re-sorting.
Top row is the input; below it the sorted squares.
Input:  nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2

nums-7-32311
squares49949121
negative — squares in reverse order
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 non-decreasing.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The largest squares come from the extremes (most negative or most positive). So fill the output from the back using two pointers at both ends.

This beats the trivial "square then sort" O(n log n) with a clean O(n) merge.

Approach

  1. Pointers l, r at both ends; write position at the end of the output.
  2. Compare squares at l and r; place the larger at the current output slot and move that pointer inward.
  3. Repeat until the pointers cross.

Walkthrough

nums = [-4,-1,0,3,10]
squares extremes: 16 vs 100 -> place 100
16 vs 9 -> 16 ... result [0,1,9,16,100]

Complexity

  • Time — O(n): single two-pointer pass.
  • Space — O(n): the output array (O(1) beyond it).

Common Pitfalls

  • Fill the result from the back. The two-pointer walk produces the largest square first, so writing forward puts the biggest value at index 0 and gives 100 0 1 9 16 instead of 0 1 9 16 100.
  • Compare absolute values, not raw values. The largest square sits at whichever end is furthest from zero, which on an array with negatives is the left end -- comparing raw values picks the wrong end and returns 16 1 0 9 100.

Full Solution — all languages

class Solution:
    def sortedSquares(self, nums):
        n = len(nums)
        res = [0] * n
        lo, hi, k = 0, n - 1, n - 1
        while lo <= hi:
            if abs(nums[lo]) > abs(nums[hi]):
                res[k] = nums[lo] * nums[lo]
                lo += 1
            else:
                res[k] = nums[hi] * nums[hi]
                hi -= 1
            k -= 1
        return res
Asked at Deutsche Bank Uber
SensAI
Beta
Tap the mic to stop voice mode