easyTwo PointersTwo Pointers

Squares of a Sorted Array

easyTime: O(n)Space: O(n)

Recognize the pattern

the existing order is part of the cluein-place modificationtwo ends moving inward

Brute force idea

A straightforward first read of Squares of a Sorted Array is this: Square each element, then sort the result. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

A calmer way to see Squares of a Sorted Array is this: Use two pointers at both ends; the larger absolute value goes at the back of the result. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Squares of a Sorted Array is this: The largest square is always at one of the two ends of the sorted array. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

One easy way to drift off course in Squares of a Sorted Array is this: Forgetting that negative numbers squared can be larger than positive ones. The fix is usually to return to the meaning of each move, not just the steps themselves.

Two Pointers Pattern