Problem
Given a sorted integer array nums in non-decreasing order, return a new array containing the squares of each number, also sorted in non-decreasing order.
Negative numbers become positive after squaring, so the order may change.
Example
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]
Approach
Since the array is already sorted, the largest square will come from either the leftmost negative number or the rightmost positive number.
Steps:
Use two pointers – one at the start and one at the end.
Compare the absolute values of both numbers.
Square the larger one and place it at the end of the result array.
Move the pointer and continue.
This method keeps the result sorted efficiently.
Python Code
class Solution:
def sortedSquares(self, nums: list[int]) -> list[int]:
n = len(nums)
result = [0] * n
left = 0
right = n - 1
pos = n - 1
while left <= right:
if abs(nums[left]) > abs(nums[right]):
result[pos] = nums[left] * nums[left]
left += 1
else:
result[pos] = nums[right] * nums[right]
right -= 1
pos -= 1
return result
Output
[4,9,9,49,121]
Top comments (0)