DSA AnimatorDSA animations
Squares of a Sorted Array LC #977 Easy Two Pointers
Problem

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

Example 1
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring: [16,1,0,9,100]. After sorting: [0,1,9,16,100].
Constraints: 1 ≤ nums.length ≤ 10⁴  |  −10⁴ ≤ nums[i] ≤ 10⁴  |  Sorted
Try Examples
Custom:
Approach
Two Pointers from Ends — Fill Result from Back
The largest square is always at one of the two ends (most positive or most negative). L points to the left end, R to the right. Compare |nums[L]|² vs |nums[R]|², write the larger one at result[p], move inward. O(n) — no sort needed!
Arrays
Variables
L pointer
—
R pointer
—
p (write)
—
written
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
L=0, R=n-1, p=n-1 (write from back)
2
While L ≤ R: compare |nums[L]|² vs |nums[R]|²
3
Write the larger square at ans[p], move that pointer inward, p--
4
Return ans — sorted squares!
Time
O(n)
Space
O(n)
Why It Works

In a sorted array, the largest absolute value is always at one of the two ends — either the leftmost (most negative) or rightmost (most positive). By comparing ends and filling the result array from back to front, we always place the correct largest square without sorting. The two pointers meet in the middle.

How to solve Squares of a Sorted Array

LeetCode 977 · Easy · Arrays · Pattern: Two Pointers

Why the obvious approach is slow

Squaring everything and then sorting costs O(n log n). Negative numbers break the order: minus 4 squared is bigger than 3 squared.

The key idea

The biggest square always comes from one of the two ends, because those have the largest absolute values. So use two pointers at both ends, and fill the answer from the back. Each time, place the bigger square, and move that pointer inward.

Remember

In a sorted array with negatives, the largest squares sit at the two ends. Fill the result from the back with two pointers.

Run the animation above on your own input, or watch the 1:31 video explanation of Squares of a Sorted Array with a dry run and Java code.

More Arrays problems