Editor

Squares of a Sorted List

#244 · Two pointers · Beginner · 35 XP · about 8 min

nums is a list of whole numbers sorted from smallest to largest, and some of them may be negative. Write sorted_squares(nums) that returns a new list holding the square of every number, also sorted from smallest to largest.

Squaring is what makes this interesting: -7 is the smallest number in [-7, -2, 3], but its square, 49, is the largest.

Examples

sorted_squares([-7, -2, 3])         # returns [4, 9, 49]
sorted_squares([-4, -1, 0, 3, 10])  # returns [0, 1, 9, 16, 100]
sorted_squares([1, 2, 3])           # returns [1, 4, 9]

Constraints

  • 0 <= len(nums) <= 10,000
  • -10,000 <= nums[i] <= 10,000

Note

Squaring everything and sorting the result works. For a neater solution, notice that the biggest square always comes from one of the two ends of nums, so the result can be filled in from the back without sorting at all.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.