Leetcode 977. Squares of a Sorted Array

Solving the Squares of a Sorted Array problem using a Two Pointers approach.

The original problem is here.

Two Pointers Approach

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.

When do we stop?

Code (Python)

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
            

Complexity

References