Bird
Raised Fist0
Interview Prepfast-slow-pointerseasyAmazonGoogleBloomberg

Happy Number

Choose your preparation mode4 modes available
▶
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 fill★Answer 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. You are given a circular array where each element represents a jump length and direction (positive for forward, negative for backward). The task is to determine if there exists a cycle in the array such that the cycle is longer than one element and all jumps are in the same direction. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy approach that tries to jump as far as possible from each index until a cycle is detected or no progress is made.
B. Dynamic programming to store reachable indices and detect cycles by memoization.
C. Brute force simulation from each index checking all possible cycles exhaustively.
D. Fast and slow pointer cycle detection that checks direction consistency and avoids single-element loops.

Solution

  1. Step 1: Understand problem constraints

    The problem requires detecting cycles in a circular array with direction consistency and cycle length > 1.
  2. Step 2: Identify suitable algorithm

    Fast and slow pointer cycle detection efficiently finds cycles in O(n) time while checking direction and cycle length constraints.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Fast and slow pointers detect cycles without exhaustive search [OK]
Hint: Cycle detection with direction check -> fast-slow pointers [OK]
Common Mistakes:
  • Assuming greedy jumps always find cycles
  • Using DP which is inefficient here
  • Brute force is correct but not optimal
2. Identify the bug in the following code snippet for finding the duplicate number using Floyd's cycle detection:
medium
A. The initialization of slow and fast pointers is incorrect
B. The second while loop incorrectly updates fast pointer
C. The first while loop condition causes an infinite loop
D. The return statement should return fast instead of slow

Solution

  1. Step 1: Examine the first while loop condition

    The loop condition is while slow != fast, but slow and fast are initialized to the same value, so the loop never runs, causing no intersection point found.
  2. Step 2: Understand consequences

    Without the loop running, slow and fast pointers do not move, so the algorithm fails to detect the cycle and returns incorrect result or loops infinitely if code is modified.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Loop condition must allow first iteration; using while True with break is correct [OK]
Hint: First loop must run at least once to find intersection [OK]
Common Mistakes:
  • Using while slow != fast before pointers move
  • Incorrect pointer updates inside loops
  • Returning wrong pointer at the end
3. Examine the following code snippet intended to detect the start of a cycle in a linked list. Identify the line containing the subtle bug that can cause a runtime error or infinite loop.
medium
A. Line 5: fast = fast.next.next
B. Line 3: while fast:
C. Line 7: if slow == fast:
D. Line 11: while ptr1 != ptr2:

Solution

  1. Step 1: Check loop condition safety

    The loop condition only checks if fast is not None, but fast.next may be None, so fast.next.next can cause an exception.
  2. Step 2: Identify fix

    The loop condition should check both fast and fast.next to avoid null pointer exceptions.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Accessing fast.next.next without checking fast.next causes runtime error [OK]
Hint: Always check fast and fast.next before accessing fast.next.next [OK]
Common Mistakes:
  • Missing fast.next check
  • Returning meeting point as cycle start
  • Infinite loop due to wrong loop condition
4. What is the space complexity of the stack-based approach to find the nth node from the end in a singly linked list of length n?
medium
A. O(n) because all nodes are stored in the stack
B. O(1) because only a few pointers are used
C. O(n) because recursion stack is used
D. O(log n) due to divide and conquer traversal

Solution

  1. Step 1: Identify data structures used

    The stack stores every node in the list, so it holds n nodes.
  2. Step 2: Determine space complexity

    Storing all n nodes means O(n) auxiliary space is required.
  3. Step 3: Re-examine options

    O(n) because all nodes are stored in the stack states O(n) space which is correct for stack-based approach. O(1) because only a few pointers are used states O(1) which is incorrect for stack-based approach.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Stack size grows linearly with list length [OK]
Hint: Stack stores all nodes, so space is O(n) [OK]
Common Mistakes:
  • Assuming constant space due to pointers
  • Confusing recursion stack with iterative stack
  • Thinking divide and conquer applies here
5. If the linked list allows cycles (i.e., it may not terminate), which modification is necessary to safely find the nth node from the end?
hard
A. Use the two-pointer approach without changes; it will still work.
B. Use a stack to store nodes indefinitely until nth node is found.
C. First detect cycle using Floyd's cycle detection, then handle accordingly before finding nth node.
D. Increase n to a very large number to ensure traversal covers the cycle.

Solution

  1. Step 1: Understand cycle impact

    If the list has a cycle, naive traversal will loop infinitely, breaking the algorithm.
  2. Step 2: Detect and handle cycle

    Use Floyd's cycle detection to identify cycle presence and length, then adjust logic to avoid infinite loops.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Cycle detection is prerequisite for safe traversal [OK]
Hint: Detect cycle first to avoid infinite loops [OK]
Common Mistakes:
  • Assuming list always terminates
  • Using stack without cycle check
  • Increasing n arbitrarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard