Solving the Squares of a Sorted Array problem using a Two Pointers approach.
The original problem is here.
The brute force approach is square $(O(N))$ and then sort $(O(N \log N))$. So the total time complexity is $O(N \log N)$. However, this is a stupid approach because it does not use the fact that the original array is sorted. The follow-up question calls for $O(N)$ time complexity.
nums[0] is the negative number with the largest magnitude. nums[n-1] is the positive number with the largest magnitude.left and right pointers. We square the larger one, place it at the result array from the end, and move the corresponding pointer inward.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