Statement▼
You are given an integer array, nums
, sorted in non-decreasing order. Your task is to return a new array containing the squares of each number, also sorted in non-decreasing order.
Constraints:
1≤ nums.length
≤103 −104≤ nums[i]
≤104 nums
is sorted in non-decreasing order.
Solution
As the input array is already sorted in non-decreasing order, we can solve this problem more efficiently than simply squaring all elements and sorting again (which would take
To take advantage of this, we use a two pointer technique: one pointer starts at the beginning of the array and the other at the end. At each step, we compare the absolute values at these two positions. The larger absolute value produces the larger square, which we place at the current last available position in the result array. We then move the pointer corresponding to the chosen value inward and continue the process.
By filling the result array from right to left, we ensure all elements are squared and placed in sorted order in a single pass, giving an optimal solution.
The steps of the algorithm are as follows:
Initialize two pointers:
left = 0
at the start andright = n - 1
at the end of the array.Create a result array
res
of the same size to store the sorted squares.Set a position marker
pos = n - 1
to fillres
from the back.While
left <= right
:Compare
abs(nums[left])
andabs(nums[right])
.Square the larger one and place it at
res[pos]
.Move the corresponding pointer inward (
left++
orright--
).Decrement
pos
to move leftward in the result array.
Once the iteration finishes,
res
contains all squares in sorted non-decreasing order.
Let’s look at the following illustration to get a better understanding of the solution: