Practice
def isHappy(n: int) -> bool:
cycle_set = {4, 16, 37, 58, 89, 145, 42, 20}
def get_next(number):
total_sum = 0
while number > 0:
digit = number % 10
total_sum += digit * digit
number //= 10
return total_sum
while n != 1 and n not in cycle_set:
n = get_next(n)
return n == 1
print(isHappy(7))
Solution
Step 1: Trace the sequence starting from 7
7 -> 49 (4²+9²=16+81=97) -> 97 -> 130 -> 10 -> 1 Detailed steps: 7 -> 49 (4²+9²=16+81=97) 97 -> 130 (9²+7²=81+49=130) 130 -> 10 (1²+3²+0²=1+9+0=10) 10 -> 1 (1²+0²=1+0=1) So it reaches 1.Step 2: Check if the code returns true for n=7
The loop terminates when n == 1, so the function returns true.Final Answer:
Option C -> Option CQuick Check:
Sequence reaches 1 -> returns true [OK]
- Miscompute sum of squares leading to wrong cycle detection
nth_from_end(head, 3) where head is a linked list with values [5, 10, 15, 20]?Solution
Step 1: Trace stack contents after traversal
Stack after pushing nodes: [5, 10, 15, 20]Step 2: Pop
Pop 1: 20, Pop 2: 15, final pop returns 10 which is the 3rd from endn-1=2times and then pop once more for valueFinal Answer:
Option D -> Option DQuick Check:
3rd from end in [5,10,15,20] is 10 [OK]
- Off-by-one popping
- Returning node instead of value
- Confusing index from front vs end
Solution
Step 1: Understand problem constraints
The problem requires splitting into k parts with sizes differing by at most one, favoring earlier parts to be larger.Step 2: Identify approach that meets constraints efficiently
Calculating total nodes first allows precise part sizes and a single pass to split, ensuring correctness and efficiency.Final Answer:
Option D -> Option DQuick Check:
Precomputing sizes avoids guesswork and multiple passes [OK]
- Assuming greedy without counting nodes works
- Trying DP unnecessarily
- Splitting without breaking links properly
Solution
Step 1: Analyze fast and slow pointer traversal
Fast pointer moves twice as fast as slow, so they meet within O(n) steps.Step 2: Count cycle length with a single traversal
After detection, counting cycle length requires traversing the cycle once, which is O(k) ≤ O(n).Final Answer:
Option A -> Option AQuick Check:
Overall time is linear in number of nodes [OK]
- Assuming counting cycle length is O(n²)
- Confusing space complexity with time
- Thinking recursion or extra data structures are used
Solution
Step 1: Identify recursion depth
The recursion visits each node once, so the call stack depth is n.Step 2: Understand space usage
No extra arrays or data structures are used, but the recursion stack itself uses O(n) space.Final Answer:
Option D -> Option DQuick Check:
Recursion stack proportional to list length n [OK]
- Assuming recursion uses constant space
- Confusing recursion with divide-and-conquer halving
- Thinking auxiliary arrays are used
