CA 18 - Squares of a Sorted Array

Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

    Input: nums = [-4,-1,0,3,10]

    Output: [0,1,9,16,100]

    Explanation: After squaring, the array becomes [16,1,0,9,100].

                         After sorting, it becomes [0,1,9,16,100].

Example 2:

    Input: nums = [-7,-3,2,3,11]

    Output: [4,9,9,49,121]


CODE:

    Here the problem can be solved by, simply squaring the elements in the array and then sort it, but it will give as the time complexity of O(nlogn) but in question they have also given if could solve this problem in O(n) time complexity, thus we go with the optimized approach. 

    In this method we will take the give statement that the given array is sorted in non-decreasing order into our leverage and solve this with two-pointer technique. Place the left and right pointer on the both the edges and check for absolute max from both of these and square the element and add to the result array, finally move the added pointer to the next element. Finally return the reverse of the result array. Thus, the expected array is obtained.


class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        res = []
        l=0
        r=len(nums)-1
        while l<=r:
            if nums[l]**2 > nums[r]**2:
                res.append(nums[l]**2)
                l+=1
            else:
                res.append(nums[r]**2)
                r-=1
        return res[::-1]

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries