Practice
Solution
Step 1: Trace initial list and first iteration
Start with current at first node (1). current.next is also 1, so duplicate detected; remove second node by linking current.next to current.next.next (node with value 2).Step 2: Continue iteration
Now current.next is 2, which differs from current.val (1), so move current to next node (2). current.next is None, loop ends.Final Answer:
Option B -> Option BQuick Check:
Duplicates removed, final list is 1 -> 2 [OK]
- Forgetting to move current pointer after removal
Solution
Step 1: Identify operations performed
The algorithm copies the next node's value into the current node and updates the next pointer to skip the next node.Step 2: Analyze time complexity
These operations are constant time, no traversal or recursion is needed.Step 3: Consider the initial access to the node
However, if only the node to delete is given, no traversal is needed. But if only the value is given and node must be found, traversal is needed.Final Answer:
Option B -> Option BQuick Check:
Copy and pointer update are O(1) operations [OK]
- Assuming traversal from head is needed, making it O(n)
- Confusing recursion with iterative approach
- Thinking deletion involves multiple node copies
Solution
Step 1: Identify heap operations per node
Each node is pushed and popped exactly once from a heap of size ≤ k.Step 2: Calculate complexity
Heap push/pop cost is O(log k), total O(N log k) for N nodes.Final Answer:
Option D -> Option DQuick Check:
Heap size depends on k, not N, so O(N log k) [OK]
- Confusing N and k in log factor
- Assuming heap size grows with N
- Thinking sequential merges are optimal
Solution
Step 1: Identify recursion depth
In the worst case, recursion proceeds one node at a time, leading to O(n) recursive calls on the stack.Step 2: Analyze space usage
No auxiliary data structures like hash sets are used, so extra space is only recursion stack space, which is O(n).Final Answer:
Option D -> Option DQuick Check:
Recursive calls stack up to list length [OK]
- Assuming O(1) space since no explicit data structures
- Confusing recursion depth with log n
- Thinking hash sets are used
def swapPairs(head: ListNode) -> ListNode:
def helper(node):
if not node or not node.next:
return node
first = node
second = node.next
# Bug: missing update of first.next to recursive call
second.next = first
return second
return helper(head)
What is the root cause of the bug?Solution
Step 1: Identify pointer updates in recursion
The correct approach sets first.next = helper(second.next) to link swapped pairs recursively.Step 2: Analyze missing update
Without updating first.next, the rest of the list is disconnected, causing lost nodes after the first swapped pair.Final Answer:
Option D -> Option DQuick Check:
Missing first.next update breaks list continuity [OK]
- Forgetting to link swapped pairs recursively
- Returning wrong node as new head
