← Back to DSA Animator
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.