easyTwo PointersTwo Pointers

Squares of a Sorted Array

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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