In this task, I worked on converting a sorted array into another sorted array of their squares.
The tricky part is that even though the input array is sorted, squaring negative numbers can mess up the order. For example, -4² = 16 which is bigger than 3² = 9.
What I Did
I created a function sortedSquares that takes a sorted array nums and returns a new sorted array of squared values.
How I Solved It
Instead of squaring everything and sorting again, I used a two-pointer approach.
I used three variables:
-
leftstarting from the beginning (index 0) -
rightstarting from the end (index n-1) -
posto fill the result array from the back
At each step:
- I compare the absolute values of
nums[left]andnums[right] - The larger absolute value will give the larger square
- I place that square at the current
posin the result array - Then move the corresponding pointer (
leftorright) - Decrease
posto fill the next position
This way, I build the sorted squared array from the back.
Code
class Solution:
def sortedSquares(self, nums):
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] ** 2
left += 1
else:
result[pos] = nums[right] ** 2
right -= 1
pos -= 1
return result
How It Works
The function avoids re-sorting by intelligently comparing values from both ends. Since the largest square will always come from either the most negative or most positive number, we place it at the end and move inward.
This reduces time complexity to O(n) instead of O(n log n).
Top comments (0)