Squares of a Sorted Array

(#977), Easy

Category: Array, Two Pointer, Sorting

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

Brute Force with Sort

  • Loop through the array and square each element.
  • Sort the resulting array using `.sort((a, b) => a - b)` to ensure numerical order.
  • Return the sorted array.
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