Squares in Order

EasyTwo Pointers≈ 15 min

You are given a list of integers nums, sorted from smallest to largest. Some of them may be negative. Return a list of the squares of every number, also sorted from smallest to largest.

Examples

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

In the first example, squaring gives [16, 1, 0, 9, 100]: the negative numbers' squares are out of order, and have to move.

Constraints

  • Between 0 and 10,000 numbers, sorted, each between -10,000 and 10,000.
  • Aim for O(n): the list is already sorted, so there is no need to sort the squares. Sorting them, at O(n log n), passes too.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 3 visible cases here, in your browser. Submit runs all 8 on the judge, 5 of them hidden, and measures how your solution scales.