Squares of Sorted Array

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Squares of Sorted Array

Approach

Use two pointers at both ends of the sorted array. Compare the absolute values (squares) at each pointer, place the larger square at the end of the result array, and move that pointer inward. Fill the result from right to left.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Two Pointers (Converging)

Why It Works

In a sorted array with negatives, the largest squares are at the extremes. By comparing from both ends and filling the result backwards, we produce a sorted output in one pass.

Updated Feb 2026