KatInterview

Build the Hailstone Number Chain

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationsimulationiterationmathematical-sequences

Last updated

Simulating an iterative number transformation until a fixed point is reached, handling boundary conditions and large intermediate values.

A hailstone sequence transforms a positive integer through repeated steps: when the current value is even, divide it by two; when odd, replace it with triple the value plus one. Continue until reaching the value 1, then stop.

Your task is to generate the complete chain of numbers visited during this transformation, starting from a given positive integer and ending at 1.

Write a function that produces this sequence as a list.

Rules

  • Include the starting number as the first element
  • Include 1 as the final element
  • Each intermediate element follows from applying the transformation rule to the previous element
  • Stop immediately upon reaching 1—do not apply further transformations
  • When the starting number is already 1, return a single-element list containing just 1

Constraints

  • 1 <= n <= 10^6
  • The sequence length will not exceed 525 elements
  • Intermediate values may grow beyond 2^31 - 1 but remain below 2^53
  • All starting values in the given range eventually reach 1

Examples

Example 1

Input: hailstone_chain(6)

Output: [6, 3, 10, 5, 16, 8, 4, 2, 1]

Example 2

Input: hailstone_chain(1)

Output: [1]

Example 3

Input: hailstone_chain(7)

Output: [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

Hints

Hint 1

Track the current value and repeatedly transform it, recording each result in order until you hit 1.

Hint 2

Check your loop termination carefully: the value 1 should appear exactly once at the end.

Hint 3

Use integer division (// in Python) to avoid floating-point results when halving even numbers.