~/problems / 1-D dynamic programming / Intro DP

Collatz Sequence Steps

medium ~25 min AirbnbBloomberg

Take a positive integer and keep applying one rule until you reach 1: halve it if it is even, otherwise triple it and add one. The number of rule applications is the number's Collatz steps. For example 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 takes 8 steps, and 1 takes 0.

Implement two functions:

  • collatz_steps(n: int) -> int: the steps for one n (1 <= n <= 10**15; intermediate values may grow far past n).
  • longest_chains(limits: list[int]) -> list[tuple[int, int]]: for each L in limits, the starting number x in 1..L with the most steps, and that step count, as (x, steps). On a tie, the smallest x wins. Answers come back in the order of limits.
collatz_steps(6)                  # 8
collatz_steps(1)                  # 0
collatz_steps(27)                 # 111
longest_chains([1, 3, 10, 6])     # [(1, 0), (3, 7), (9, 19), (6, 8)]

limits can hold 100,000 values, each up to 500,000. Walking every chain from scratch repeats the same tails millions of times and is far too slow.

Show hint

Compute steps for every number up to max(limits) in increasing order into a list. When the walk from n drops below n, the rest of the chain is already known: add the stored count and stop. Then a running "best so far" per L answers each query in O(1).

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc