Squares of a Sorted Array(#977)
Category: Array, Two Pointer, Sorting, Foundation
๐งฉ Problem Statement
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.
๐ Examples
Input: nums = [-4, -1, 0, 3, 10]
Output: [0, 1, 9, 16, 100]
Explanation: Square each element: [16, 1, 0, 9, 100] โ sort the array to get [0, 1, 9, 16, 100].
๐ง Approach
โข Loop through the array and square each number.
โข Use JavaScript's `.sort()` method with a custom comparator to sort numerically.
Important: `.sort()` sorts strings by default, so we use `(a, b) => a - b` for numeric sort.
๐ป Code
var sortedSquares = function(nums) {
for (let i = 0; i < nums.length; i++) {
nums[i] = nums[i] * nums[i];
}
return nums.sort((a, b) => a - b);
};
console.log(sortedSquares([-4, -1, 0, 3, 10])); // Output: [0, 1, 9, 16, 100]
๐ Complexity
Time: O(n log n)
Space: O(1) (in-place, ignoring output array if returned separately)