call(back)
Algorithms & Data StructureseasySign in to star problems

Happy Number Cycle

Repeatedly replace a positive integer by the sum of the squares of its digits. The sequence always ends in a loop: a happy number reaches 1 and stays there, and every other number falls into the same eight-value loop. Return the loop the given number enters, as its values in the order they are visited, starting from the first value that is visited twice.

happyCycle(19)   ->  [1]                                 // 19 → 82 → 68 → 100 → 1 → 1 …
happyCycle(2)    ->  [4, 16, 37, 58, 89, 145, 42, 20]    // 2 → 4 → 16 → … → 20 → 4
happyCycle(116)  ->  [58, 89, 145, 42, 20, 4, 16, 37]    // the same loop, entered at 58

Hints

Hint 1

Keep the values in order and a set of what has been seen; stop at the first value that is already in the set.

Hint 2

The loop is the slice of the path from that value's first appearance to the end.

Hint 3

For O(1) extra space, Floyd's two pointers find a value inside the loop; walk from it until it comes round again to list the loop.

Topics

Asked at

Similar Problems6