sagelearnai

Squares of a Sorted Array

Difficulty: Easy · Pattern: Two Pointers · LeetCode #977

Given nums sorted in non-decreasing order (it may contain negatives), return the squares of each number, sorted in non-decreasing order, in O(n).

Examples

text
[-4, -1, 0, 3, 10]  →  [0, 1, 9, 16, 100]
[-7, -3, 2, 3, 11]  →  [4, 9, 9, 49, 121]

Hints

  1. Squaring and sorting is O(n log n). Where is the largest square?
  2. It's at one of the two ends. Fill the result from the back.

Approach

The largest absolute value is always at the left or right end. Compare |nums[l]| and |nums[r]|, put the larger square at the current last free position of the output, move that pointer inward, and repeat. O(n), with no sort.

Complexity

Time: O(n). Space: O(n) for the output.

Python solution
def sortedSquares(nums):
    n = len(nums)
    out = [0] * n
    l, r = 0, n - 1
    for k in range(n - 1, -1, -1):
        if abs(nums[l]) > abs(nums[r]):
            out[k] = nums[l] * nums[l]; l += 1
        else:
            out[k] = nums[r] * nums[r]; r -= 1
    return out
JavaScript solution
function sortedSquares(nums) {
  const n = nums.length, out = new Array(n);
  let l = 0, r = n - 1;
  for (let k = n - 1; k >= 0; k--) {
    if (Math.abs(nums[l]) > Math.abs(nums[r])) { out[k] = nums[l] * nums[l]; l++; }
    else { out[k] = nums[r] * nums[r]; r--; }
  }
  return out;
}