Practice
addListsHelper when adding lists representing 724 and 564?Solution
Step 1: Trace addition from least significant digit
Adding 4 + 4 = 8, carry 0; next 2 + 6 = 8, carry 0; finally 7 + 5 = 12, carry 1.Step 2: Propagate carry backward
Carry 1 is returned from the most significant digit addition, indicating an overflow digit.Final Answer:
Option A -> Option AQuick Check:
724 + 564 = 1288, carry 1 at MSB addition [OK]
- Ignoring carry from most significant digit
- Off-by-one error in recursion base case
- Misaligning lists before addition
Solution
Step 1: Identify auxiliary space usage
The algorithm uses recursion that goes as deep as the length of the list, storing one frame per node.Step 2: Understand recursion stack space
Each recursive call adds a frame to the call stack, so total auxiliary space is O(n). No extra arrays are created.Final Answer:
Option A -> Option AQuick Check:
Recursion depth equals list length -> O(n) space [OK]
- Assuming O(1) because no explicit arrays
- Confusing recursion with divide-and-conquer log n space
- Mistaking array approach space for recursion approach
Solution
Step 1: Understand pointer updates
When duplicates are found, current.next is updated to skip duplicate nodes; current pointer stays to check next node.Step 2: Identify bug in pointer advancement
If current pointer is moved unconditionally after removal, it may skip nodes or cause infinite loops. The else clause must move current only when no duplicate is removed.Final Answer:
Option A -> Option AQuick Check:
Incorrect pointer advancement causes skipping or infinite loops [OK]
- Advancing current pointer after removing duplicates
def reverseList(head):
def helper(prev, curr):
if not curr:
return prev
curr.next = prev
next_temp = curr.next
return helper(curr, next_temp)
return helper(None, head)Solution
Step 1: Analyze pointer updates
Line 5 assigns next_temp = curr.next after curr.next is set to prev, so next_temp points to prev, not the original next node.Step 2: Consequence of bug
Because next_temp is incorrect, recursion loses the rest of the list, causing incomplete reversal or infinite loops.Final Answer:
Option C -> Option CQuick Check:
Saving next node before pointer reversal is critical [OK]
- Swapping order of pointer updates
- Forgetting to set head.next to None in recursion
Solution
Step 1: Understand circular list implications
In a circular list, traversal never ends naturally, so counting nodes or recursion can loop infinitely.Step 2: Break the cycle
Temporarily breaking the cycle converts it to a linear list, allowing standard removal algorithms to work correctly.Step 3: Restore circular link if needed
After removal, reconnect the last node to the new head to restore circularity.Final Answer:
Option B -> Option BQuick Check:
Breaking cycle prevents infinite loops and enables standard logic [OK]
- Assuming two-pointer works on circular lists
- Using recursion without cycle detection
- Using extra space unnecessarily
