75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

977. Squares of a Sorted Array

O(NlogN) Time solution

Code

class Solution{
public:
    vector<int> sortedSquares(vector<int> &nums)
    {
        vector<int> ans;
        for (auto &x : nums)
            ans.emplace_back(x * x);

        sort(ans.begin(), ans.end());
        return ans;
    }
};

O(N) Time solution

Code

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        vector<int> ans(nums.size(),0);
        int l = 0, r = nums.size()-1;
        int i = nums.size()-1;
        while(l<=r){
            if(abs(nums[l])>abs(nums[r])){
                ans[i--]=nums[l]*nums[l];
                l++;
            }else{
                ans[i--]=nums[r]*nums[r];
                r--;
            }
        }
        return ans;
    }
};