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.

You must solve this problem efficiently, considering that the input array is already sorted.

Input & Output

Example 1 — Mixed Positive and Negative
$ Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
💡 Note: Squares are [16,1,0,9,100]. After sorting: [0,1,9,16,100]. Note that negative numbers become positive when squared.
Example 2 — All Negative Numbers
$ Input: nums = [-7,-3,-2,-1]
Output: [1,4,9,49]
💡 Note: All numbers are negative. Squares are [49,9,4,1]. After sorting in non-decreasing order: [1,4,9,49].
Example 3 — All Positive Numbers
$ Input: nums = [1,2,3,4,5]
Output: [1,4,9,16,25]
💡 Note: All numbers are positive and already sorted. Squares maintain the same order: [1,4,9,16,25].

Constraints

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

Visualization

Tap to expand
Squares of a Sorted ArrayInput (Sorted)-4-10310Square Each Element16109100Sort Result01916100Output: [0, 1, 9, 16, 100]
Understanding the Visualization
1
Input
Sorted array [-4,-1,0,3,10] with mixed signs
2
Process
Square each element: [16,1,0,9,100]
3
Output
Sort squared values: [0,1,9,16,100]
Key Takeaway
🎯 Key Insight: Use two pointers to identify largest squares from array extremes, avoiding the need to sort
Asked in
Facebook 35 Amazon 28 Microsoft 22 Apple 18
125.0K Views
High Frequency
~15 min Avg. Time
4.3K 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