Squares of a Sorted Array - 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.

The challenge lies in the fact that negative numbers, when squared, become positive and can potentially be larger than the squares of positive numbers. For example, (-4)² = 16 while 3² = 9, so -4 squared is actually larger than 3 squared!

Goal: Transform each element to its square while maintaining sorted order in the result.

Example: [-4, -1, 0, 3, 10][0, 1, 9, 16, 100]

Input & Output

example_1.py — Basic Case
$ Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
💡 Note: After squaring, we get [16,1,0,9,100]. After sorting, we get [0,1,9,16,100].
example_2.py — All Negative
$ Input: nums = [-7,-3,-2,-1]
Output: [1,4,9,49]
💡 Note: After squaring, we get [49,9,4,1]. After sorting, we get [1,4,9,49].
example_3.py — All Positive
$ Input: nums = [1,2,3,4,5]
Output: [1,4,9,16,25]
💡 Note: Since all numbers are positive and already sorted, their squares remain in sorted order.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
🥊 The Square Battle ArenaTwo competitors fight for the biggest square!Left Competitor-4Square: 16Right Competitor10Square: 10016 vs 100🏆 100 WINS!Victory Podium (Result Array)16100👑🔄 Next Round: Move Right Pointer Left-4-10310LR💡 Key Insight: The extremes (ends) always have the largest squares!Continue until all battles are won and the result is complete
Understanding the Visualization
1
Set Up Battle Arena
Place pointers at both ends - these represent our 'competitors'
2
Square Off
Calculate squares of both competitors
3
Winner Takes Position
The larger square wins and gets placed in the result
4
Next Round
Move the winning pointer inward and repeat
Key Takeaway
🎯 Key Insight: In a sorted array, the largest absolute values (and thus largest squares) are always at the ends. The two-pointer approach leverages this property to build the result efficiently in O(n) time.
Asked in
Google 45 Amazon 38 Meta 28 Microsoft 22
42.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen