Python coding

Squares back in order

nums is sorted in non-decreasing order and may hold negatives. Return a new list with the square of every value, also sorted in non-decreasing order. For [-3, -1, 0, 2, 4] the answer is [0, 1, 4, 9, 16].

nums may be empty. Squaring and then sorting costs O(n log n): aim for one O(n) pass, without calling a sort.

  • sorted_squares([-3,-1,0,2,4]) → [0,1,4,9,16]
  • sorted_squares([-8,-2,1,3,9]) → [1,4,9,64,81]
  • sorted_squares([1,2,3]) → [1,4,9]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Squares of the negatives fall as you move right, squares of the rest rise. So the largest square is always at one of the two ends, never in the middle.

Hint 2

Put lo at the start and hi at the end. Write the larger of the two squares into the last free slot of the output, then move that pointer inward.

Solution and why it works
pythonO(n) · O(n) for the output
def sorted_squares(nums: list[int]) -> list[int]:
    out = [0] * len(nums)
    lo, hi = 0, len(nums) - 1
    for k in range(len(nums) - 1, -1, -1):   # fill from the largest square down
        if abs(nums[lo]) > abs(nums[hi]):
            out[k] = nums[lo] * nums[lo]
            lo += 1
        else:
            out[k] = nums[hi] * nums[hi]
            hi -= 1
    return out

Reading left to right, the squares fall through the negatives and rise after them: a valley. So the largest remaining square is always at lo or hi: compare the two ends, write the bigger one into the last free slot, and step that end inward. The trap is filling from the front: the smallest square hides somewhere at the bottom of the valley, but the largest is always at an end.

Related lab: Loops in motion