Leetcode 1019 Solution

This article provides solution to leetcode question 1019 (squares-of-a-sorted-array)

https://leetcode.com/problems/squares-of-a-sorted-array

Solution

class Solution(object):
    def sortedSquares(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        ans = []

        for i in range(len(A)):
            if A[i] >= 0:
                break

        l = i - 1
        r = i

        while l >= 0 or r < len(A):
            left_val = -A[l] if l >= 0 else sys.maxint
            right_val = A[r] if r < len(A) else sys.maxint

            if left_val < right_val:
                ans.append(left_val ** 2)
                l -= 1
            else:
                ans.append(right_val ** 2)
                r += 1

        return ans