In this task, I worked on converting a sorted array into another sorted array of their squares.
Even though the input array is sorted, squaring the numbers can disturb the order (because of negative numbers). So we need a smart way to keep the result sorted.
MY APPROACH
I created a function that takes a sorted array and returns a new array containing the squares of each number in sorted order.
EXAMPLE
Input : nums = [-4, -1, 0, 3, 10]
output : [0,1,9,16,100]
LOGIC IMPLEMENTED
Instead of squaring and sorting again, I used a two-pointer approach:
- One pointer at the start
- One pointer at the end
- Initialize:
- left = 0
- right = n-1
- Create a result array
- Compare:
- Square of left element
- Square of right element Place the larger square at the end and move pointers
class Solution:
def sortedSquares(self, nums):
n = len(nums)
result = [0] * n
left = 0
right = n - 1
pos = n - 1
while left <= right:
if nums[left]**2 > nums[right]**2:
result[pos] = nums[left]**2
left += 1
else:
result[pos] = nums[right]**2
right -= 1
pos -= 1
return result
Top comments (0)