A two-pointer inward traversal approach to square each number and sort the array in O(n) time
Original problem is here.
nums[0] is the negative number with the largest magnitude. nums[n-1] is the positive number with the largest magnitude.As we move the pointers inward by one index, we encounter the next largest magnitude numbers.
left and right pointers. We take the larger square, place it into the result array from the end, and move the corresponding pointer inward.left points to 0 (the first element).right points to n - 1 (the last element).result array of size $N$: result = [0] * n.while loop that continues as long as left <= right.sq_left = nums[left]**2 and sq_right = nums[right]**2.index_result = right - left.sq_left < sq_right: sq_right into result[index_result] and move right inward (right -= 1).sq_left into result[index_result] and move left inward (left += 1).left > right, all $N$ elements have been processed and placed into result.class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
result = [0]*n
left = 0
right = n-1
while left <= right:
sq_left = nums[left]**2
sq_right = nums[right]**2
index_result = right-left
if sq_left < sq_right:
result[index_result] = sq_right
right -=1
else:
result[index_result] = sq_left
left += 1
return result