Squares of a Sorted Array
Squares of a Sorted Array Problem You’re given a sorted array (in non-decreasing order), which may include negative numbers. The task is to return a new array of the squares of each number, also so...

Source: DEV Community
Squares of a Sorted Array Problem You’re given a sorted array (in non-decreasing order), which may include negative numbers. The task is to return a new array of the squares of each number, also sorted. Strategy The first idea is simple: square each number and sort the result. But that adds extra work. What actually matters here is this: The array is sorted, but negative numbers become large when squared So the largest values after squaring will come from 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(