977. Squares of a Sorted Array

WhereIsLijah - Aug 14 - - Dev Community

Here we employ 2 pointers to keep track of the indices

Solution:
Since it is in a non-decreasing order e.g [-4,-1,0,3,10], we need to compare values of both pointers and also keep track of the indices after each iteration.

1 - Initialize left pointer to 0, representing the start of the list.
2 - Initialize right pointer to the last index of the list (len(nums) - 1).
3 - Create an empty list result to store the squares of the elements.
4 - Loop while left is less than or equal to right:
4a - Compare the absolute values of the elements at the left and right pointers.
4b - If the absolute value of the element at left is greater than that at right, append the square of the element at left to result, and increment the left pointer by 1.
4c - Else, append the square of the element at right to result, and decrement the right pointer by 1.
5 - After the loop, reverse the result list to ensure the squares are in non-decreasing order.
6 - Return the result list, which now contains the squared values sorted in non-decreasing order.

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        left = 0
        right = len(nums)-1
        result = []

        while left <= right:
            if abs(nums[left]) > abs(nums[right]):
                result.append(nums[left] ** 2)
                left +=1
            else:
                result.append(nums[right] ** 2)
                right -=1

        result.reverse()

        return result
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . .
Terabox Video Player