🔗LC977 🟢 Easy 🧩 Pattern – Arrays and Loops
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
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].Code language: JavaScript (javascript)Solution
We use two pointers left and right and keep pushing the largest values first to the end of the result array.
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortedSquares = function (nums) {
const n = nums.length;
let left = 0; // Left pointer
let right = n - 1; // Right pointer
const output = new Array(n);
for (let i = n - 1; i >= 0; i--) {
const leftValue = nums[left] ** 2;
const rightValue = nums[right] ** 2;
if (leftValue > rightValue) {
output[i] = leftValue;
left++;
} else {
output[i] = rightValue;
right--;
}
}
return output;
};Code language: JavaScript (javascript)