← Questions

Collatz sequence steps with memoized range maximum

0
AirbnbCoding

A coding interview question asked at Airbnb. It tests memoization, simulation and math.

Starting from a positive integer n, repeat the following until n equals 1:

  • If n is even, set n = n / 2.
  • If n is odd, set n = 3n + 1.

Each replacement counts as one step. (It is widely believed, though unproven, that every positive integer reaches 1.)

Part 1. Implement collatz_steps(n: int) -> int, which returns the number of steps needed to reach 1. collatz_steps(1) is 0. Raise an error for n < 1.

Part 2. Implement longest_up_to(n: int) -> tuple[int, int], which returns (start, steps) for the starting value in [1, n] that needs the most steps. If several starts tie, return the smallest. Your solution should handle n up to 1,000,000 in a few seconds, so avoid recomputing work that earlier starting values already did.

Example 1

collatz_steps(6) -> 8
# 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

Example 2

longest_up_to(10) -> (9, 19)
# 9 needs 19 steps; no start from 1 to 10 needs more.

Constraints

  • 1 <= n <= 10^6 for Part 2.
  • Intermediate values can grow far larger than n (starting from 27, the sequence climbs past 9,000).

Clarifying questions

  • Should Part 1 also use the cache built by Part 2?
  • Is recursion allowed, given that some sequences take hundreds of steps?
  • How much memory may the cache use: a dict of every value seen, or only values up to n?
  • Should the function reject non-integers as well as n < 1?

What a strong answer covers

  • Part 1 is a loop that counts steps until 1 and raises for n < 1.
  • Part 2 memoizes steps in an array of size n + 1. For each start, it follows the sequence until it reaches a value below the start (whose count is already known), counts the steps taken, and fills in the values on the way that are within the array.
  • Keeps the walk iterative with a small list of visited values, so no recursion depth issues, and uses plain integers since values can grow past n.
  • Tracks the maximum with a strict > comparison so the smallest start wins a tie.
  • Tests: both examples, n = 1 ((1, 0)), a known value such as 27 (111 steps), and a check of the memoized result against the plain loop for every start up to 1,000.

Follow-ups

  • Answer longest_up_to for many different n: precompute once and keep a running maximum.
  • Speed it up further: skip every start at or below n / 2, since 2x takes one more step, or take several steps at once.
  • Return the highest value reached by any sequence up to n.
  • Generalize the rule to an + b and detect sequences that loop instead of reaching 1.

Where it's asked

What it tests

memoization · simulation · math

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding