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
📋
Problem

Imagine a number game where you repeatedly replace a number by the sum of the squares of its digits. Will you eventually reach 1, or get stuck in a loop forever?

Given a positive integer n, determine if it is a happy number. A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Return true if n is a happy number, and false if not.

1 ≤ n ≤ 10^5
Edge cases: 1 → true (smallest happy number)2 → false (enters cycle)7 → true (happy number)
</>
IDE
def isHappy(n: int) -> bool:public boolean isHappy(int n)bool isHappy(int n)function isHappy(n)
def isHappy(n: int) -> bool:
    # Write your solution here
    pass
class Solution {
    public boolean isHappy(int n) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool isHappy(int n) {
    // Write your solution here
    return false;
}
function isHappy(n) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: true for input 2Missing cycle detection causes infinite loop or incorrect true return.Implement cycle detection using a set or fast-slow pointers to detect repeated numbers.
Wrong: false for input 1No base case handling for n=1, causing unnecessary processing and wrong output.Add early return if n == 1 to return true immediately.
Wrong: true for input 4Fails to detect cycle in sequence, incorrectly assuming happiness.Use Floyd's cycle detection or a set to detect cycles and return false if cycle found without 1.
Wrong: true for input 3Assuming all numbers eventually reach 1 without cycle detection.Implement cycle detection to identify non-happy numbers that cycle endlessly.
Wrong: TLE on large input 99999Using set-based cycle detection with large input causing time limit exceeded.Switch to Floyd's fast-slow pointer cycle detection to reduce time and space complexity.
Test Cases
t1_01basic
Input19
Expectedtrue

19 leads to 1 through sum of squares sequence: 19 -> 82 -> 68 -> 100 -> 1

t1_02basic
Input7
Expectedtrue

7 leads to 1 through sequence: 7 -> 49 -> 97 -> 130 -> 10 -> 1

t2_01edge
Input1
Expectedtrue

1 is the smallest happy number by definition.

t2_02edge
Input2
Expectedfalse

2 enters a cycle and never reaches 1, so it is not happy.

t2_03edge
Input100000
Expectedtrue

100000 reduces to 1 through sum of squares sequence: 100000 -> 1

t3_01corner
Input4
Expectedfalse

4 enters a known cycle (4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4) and is not happy.

t3_02corner
Input19
Expectedtrue

Test to catch greedy approach that assumes any number with digit 1 is happy; 19 is happy but must be confirmed by full sequence.

t3_03corner
Input3
Expectedfalse

3 enters a cycle and is not happy; tests confusion between 0/1 and unbounded sequences.

t4_01performance
Input99999
⏱ Performance - must finish in 2000ms

Input n=99999 tests performance of cycle detection algorithm with O(k * log n) complexity; must complete within 2 seconds.

Practice

(1/5)
1. Consider the following code that detects a cycle by marking nodes as visited. Given the linked list: 1 -> 2 -> 3 -> 4 -> 2 (cycle back to node with value 2), what is the output of hasCycle(node1)?
easy
A. true
B. false
C. null
D. Runtime error due to infinite loop

Solution

  1. Step 1: Trace the traversal and marking of nodes

    Start at node1 (visited=false), mark visited=true, move to node2. Repeat for node2 and node3. When reaching node4, mark visited=true and move to node2 again, which is already visited.
  2. Step 2: Detect cycle when revisiting node2

    Since node2.visited is true, the function returns true indicating a cycle.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Cycle detected correctly by visited flag [OK]
Hint: Cycle detected when revisiting a marked node [OK]
Common Mistakes:
  • Assuming no cycle due to missing pointer update
  • Confusing return values
2. You are given a singly linked list and need to find the node that is exactly in the middle of the list. Which approach guarantees finding the middle node in a single pass with constant extra space?
easy
A. Store all nodes in an array, then access the middle index directly.
B. Traverse the list twice: first to count nodes, second to reach the middle node.
C. Use two pointers: move one pointer twice as fast as the other; when the fast pointer reaches the end, the slow pointer is at the middle.
D. Use a recursive approach to reach the end and count backwards to the middle.

Solution

  1. Step 1: Understand the problem constraints

    The goal is to find the middle node in a single pass and O(1) space.
  2. Step 2: Identify the approach that uses two pointers

    Using a slow pointer moving one step and a fast pointer moving two steps ensures when fast reaches the end, slow is at the middle.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Two-pointer technique is classic for single-pass middle node [OK]
Hint: Two pointers with different speeds find middle in one pass [OK]
Common Mistakes:
  • Thinking counting then traversing is single pass
  • Using extra space unnecessarily
  • Recursion adds overhead and is not optimal
3. Given the following code, what is the output when calling nth_from_end(head, 3) where head is a linked list with values [5, 10, 15, 20]?
easy
A. 5
B. 15
C. 20
D. 10

Solution

  1. Step 1: Trace stack contents after traversal

    Stack after pushing nodes: [5, 10, 15, 20]
  2. Step 2: Pop n-1=2 times and then pop once more for value

    Pop 1: 20, Pop 2: 15, final pop returns 10 which is the 3rd from end
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    3rd from end in [5,10,15,20] is 10 [OK]
Hint: Stack top is last node; pop n times to get nth from end [OK]
Common Mistakes:
  • Off-by-one popping
  • Returning node instead of value
  • Confusing index from front vs end
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. Suppose the problem is modified so that after deleting N nodes, the deleted nodes can be reinserted later in the list (i.e., nodes can be reused). Which of the following changes to the algorithm is necessary to correctly handle this variant?
hard
A. Use a recursive approach to backtrack and reinsert deleted nodes at correct positions.
B. Maintain a separate data structure to store deleted nodes and reinsert them after traversal.
C. Modify the iterative approach to skip M nodes, delete N nodes, and immediately reattach deleted nodes after the next M nodes.
D. No change needed; the original iterative approach already supports node reuse.

Solution

  1. Step 1: Understand node reuse requirement

    Deleted nodes must be preserved and reinserted later, so they cannot be simply discarded by pointer reassignment.
  2. Step 2: Evaluate algorithm changes

    The original approach loses references to deleted nodes. To reuse, store deleted nodes externally and reinsert after traversal or at correct positions.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Maintaining deleted nodes separately enables controlled reinsertion [OK]
Hint: Reusing nodes requires storing them, not discarding pointers [OK]
Common Mistakes:
  • Assuming original approach supports reuse
  • Trying to reattach nodes immediately without storage
  • Using recursion unnecessarily