Squares of a Sorted Array
Squares of a Sorted Array Problem You’re given a sorted array that can include negative numbers. The task is to return a new array of the squares of each number, also sorted. Strategy The straightf...

Source: DEV Community
Squares of a Sorted Array Problem You’re given a sorted array that can include negative numbers. The task is to return a new array of the squares of each number, also sorted. Strategy The straightforward way is to square every element and then sort the array. But that takes extra time. What made this problem interesting is noticing this: The array is sorted, but squaring negative numbers makes them large So the largest values after squaring will be at either end of the array Because of that, I used two pointers: One at the beginning One at the end At each step, I compare their absolute values and place the larger square at the end of the result array. Code class Solution: def sortedSquares(self, nums): n = len(nums) result = [0] * n left, right = 0, 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 Key Lines Explained abs(nums