Anjan Dutta

Leet Code 977: Squares of a Sorted Array

Leet Code 977: Squares of a Sorted Array

Problem statement:

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

Constraints

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

Soultion:

/**
* @param {number[]} nums
* @return {number[]}
*/
var sortedSquares = function(nums) {
let l = 0;
let r = nums.length-1;
let arr = [];
for(let i = nums.length-1; i>=0; i--) {
const ml = nums[l]*nums[l];
const mr = nums[r]*nums[r];
if(ml>mr) {
arr[i] = ml;
l++;
} else {
arr[i] = mr;
r--;
}
}
return arr;
};