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)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources