Skip to content

visual walkthrough

Squares of a Sorted Array

EasyOpposite EndsReported at: MetaAmazonGoogle+2

Largest values sit at the ends, so you fill the output from the back.

Solve on LeetCode

The idea

In a sorted array with negatives, the largest square is at the left end (a big negative) or the right end (a big positive), never in the middle. So the squares come out biggest-first from the two ends.

Fill the result from the back, comparing the two ends and moving inward: one pass, no sorting.

Complexity

approachtimespace
Square, then sortO(n log n)O(n)
Two pointersO(n)O(n)

More walkthroughs