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 Array INPUT Sorted Array (non-decreasing) -4 -1 0 3 10 i=0 i=1 i=2 i=3 i=4 Two Pointers Technique left right Squares: 16 1 0 9 100 Larger squares at edges! nums = [-4,-1,0,3,10] ALGORITHM STEPS 1 Initialize Pointers left=0, right=n-1 result[n-1] (fill from end) 2 Compare Squares |nums[left]| vs |nums[right]| Compare absolute values 3 Place Larger Square Put larger^2 at result[pos] Move corresponding pointer 4 Repeat Until Done While left <= right Decrement pos each time Iteration Example: |-4|=4 vs |10|=10 10^2=100 --> result[4] |-4|=4 vs |3|=3 4^2=16 --> result[3] FINAL RESULT Sorted Squares Array 0 1 9 16 100 OK Sorted in non-decreasing order! Output: [0, 1, 9, 16, 100] Complexity Analysis Time: O(n) Single pass through array Space: O(n) Key Insight: In a sorted array, the largest squared values are at the extremes (most negative or most positive). By using two pointers from both ends and filling result from the back, we achieve O(n) time complexity without needing to sort afterwards! TutorialsPoint - Squares of a Sorted Array | Two Pointers Optimal Approach
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