Bird
Raised Fist0
Interview Prepfast-slow-pointerseasyAmazonGoogleBloomberg

Happy Number

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Initialize cycle set and start number

The algorithm initializes the set of known cycle numbers that indicate unhappy sequences. The starting number is set to 19.

💡 This setup defines the stopping conditions: reaching 1 means happy, reaching any cycle number means unhappy.
Line:cycle_set = {4, 16, 37, 58, 89, 145, 42, 20} n = 19
💡 The cycle set is a fixed known set of numbers that cause infinite loops if the sequence reaches them.
📊
Happy Number - Watch the Algorithm Execute, Step by Step
Watching each transformation and check step-by-step reveals how the algorithm detects cycles and terminates correctly, which is hard to grasp from code alone.
Step 1/11
·Active fillAnswer cell
setup
19
compare
19
fill_cells
19
82
compare
19
82
fill_cells
19
82
68
compare
19
82
68
fill_cells
19
82
68
100
compare
19
82
68
100
fill_cells
19
82
68
100
1
compare
19
82
68
100
1
Result: true
reconstruct
19
82
68
100
1
Result: true

Key Takeaways

The algorithm detects happy numbers by iterating through a sequence generated by summing squares of digits until it reaches 1 or a known cycle.

This insight is hard to see from code alone because the sequence and cycle detection are implicit and require following the transformations step-by-step.

The known cycle set acts as a fast cycle detection mechanism to prevent infinite loops in unhappy numbers.

Understanding the role of the cycle set is easier when you see the algorithm check membership at each step visually.

Each step transforms the current number into the next, showing how the sequence evolves and why the algorithm terminates.

Watching each sum of squares calculation clarifies how the sequence progresses, which is abstract in code.

Practice

(1/5)
1. Consider the following buggy code snippet for detecting a circular array loop. Which line contains the subtle bug that causes incorrect detection of single-element loops as valid cycles?
medium
A. Line with 'if nums[i] == 0: continue' - skipping zeros prematurely
B. Line with 'if slow == fast: return True' - missing check for single-element loop
C. Line with 'direction = nums[i] > 0' - direction assignment incorrect
D. Line with 'nums[slow] = 0' - zeroing visited elements too early

Solution

  1. Step 1: Identify where single-element loops are checked

    The original code breaks if slow == next_index(slow) to avoid single-element loops.
  2. Step 2: Locate missing check

    The buggy code returns True immediately when slow == fast without verifying cycle length.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing single-element loop check causes false positives [OK]
Hint: Check cycle length before returning True to avoid single-element loops [OK]
Common Mistakes:
  • Returning True immediately on pointer meet
  • Ignoring direction consistency
  • Incorrectly zeroing elements
2. Identify the bug in the following code snippet for detecting and returning the cycle length in a linked list.
medium
A. Line 11: The length counting loop should start with length = 0 instead of 1.
B. Line 6: slow pointer should move two steps instead of one.
C. Line 7: fast pointer should move one step instead of two.
D. Line 4: The condition should check both fast and fast.next to avoid null pointer errors.

Solution

  1. Step 1: Check loop condition for pointer safety

    The loop condition only checks if fast is not null, but fast.next may be null causing runtime error on fast.next.next.
  2. Step 2: Confirm other lines are correct

    Slow moves one step, fast moves two steps correctly; length counting starts at 1 correctly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing fast.next check causes null pointer dereference [OK]
Hint: Always check fast and fast.next before advancing fast by two steps [OK]
Common Mistakes:
  • Forgetting fast.next check
  • Off-by-one in length counting
  • Swapping slow and fast pointer steps
3. Consider the following buggy code snippet for splitting a linked list into k parts. Which line contains the subtle bug that can cause parts to remain connected, leading to incorrect output or infinite loops?
medium
A. Line where current.next is set to null (missing in this code)
B. Line where parts[i] is assigned
C. Line where remainder is decremented
D. Line where total_nodes is counted

Solution

  1. Step 1: Identify missing link break

    The code comments out the lines that break the link after each part, so parts remain connected.
  2. Step 2: Understand impact

    Without setting current.next = null, parts share nodes, causing incorrect output or infinite loops.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Breaking links is essential to separate parts [OK]
Hint: Always break links to separate parts [OK]
Common Mistakes:
  • Forgetting to break links
  • Misplacing remainder decrement
  • Incorrectly assigning parts[i]
4. Suppose the array can contain multiple duplicates and some numbers appear more than twice. Which modification to Floyd's cycle detection algorithm correctly finds any duplicate number?
hard
A. No modification needed; Floyd's algorithm works regardless of duplicate count
B. Use a hash set to track visited numbers instead of cycle detection
C. Run Floyd's algorithm multiple times, removing found duplicates each time
D. Floyd's algorithm still works because the cycle corresponds to any duplicate, even if repeated

Solution

  1. Step 1: Understand Floyd's algorithm behavior with multiple duplicates

    The cycle in the array corresponds to the repeated number's indices. Even if duplicates appear multiple times, the cycle exists and Floyd's algorithm detects its entrance.
  2. Step 2: Confirm no need for multiple runs or extra data structures

    Floyd's algorithm finds one duplicate per run. It does not require modification to detect duplicates repeated more than twice.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Cycle detection finds the cycle entrance regardless of duplicate frequency [OK]
Hint: Cycle entrance corresponds to duplicate regardless of count [OK]
Common Mistakes:
  • Assuming Floyd's algorithm only works if duplicate appears twice
  • Thinking multiple runs or extra space are needed
  • Confusing cycle detection with hash-based methods
5. Suppose you want to find the middle node of a linked list, but the list is circular (the last node points back to the head). Which modification to the two-pointer approach correctly finds the middle node without infinite looping?
hard
A. Use the same two-pointer approach but add a visited set to detect cycles and stop when fast pointer revisits a node.
B. Use recursion to count nodes until the head is reached again, then find middle by index.
C. Convert the circular list to a linear list by breaking the cycle first, then apply the standard two-pointer approach.
D. Modify the loop to stop when fast or fast.next equals the head node, then return slow pointer.

Solution

  1. Step 1: Understand circular list behavior

    In a circular list, fast pointer will loop infinitely unless we detect when it cycles back to head.
  2. Step 2: Modify loop condition

    Stop when fast or fast.next equals head to avoid infinite loop; slow pointer will be at middle.
  3. Step 3: Compare alternatives

    Visited set adds extra space; breaking cycle modifies input; recursion risks stack overflow.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Stopping at head detects cycle end without extra space [OK]
Hint: Detect cycle by checking if fast pointer returns to head [OK]
Common Mistakes:
  • Using visited set wastes space
  • Breaking cycle modifies input
  • Recursion risks stack overflow