Practice
Solution
Step 1: Understand the problem constraints
The list is already sorted, so duplicates appear consecutively, allowing a single pass to remove them efficiently.Step 2: Identify the optimal approach
Iterating once and comparing each node with its next node lets us remove duplicates in-place with O(n) time and O(1) space.Final Answer:
Option C -> Option CQuick Check:
Single pass with pointer manipulation matches optimal solution [OK]
- Thinking nested loops are needed despite sorted input
n. The task is to remove the n-th node from the end of the list in one pass without using extra space. Which approach guarantees this with optimal time and space complexity?Solution
Step 1: Understand the problem constraints
The problem requires removing then-th node from the end in one pass without extra space.Step 2: Evaluate approaches
Two pointers spacednapart allow traversal in one pass, identifying the node to remove without counting or extra storage.Final Answer:
Option A -> Option AQuick Check:
Two-pointer technique is classic for single-pass linked list problems [OK]
- Thinking two passes are necessary
- Using extra space for indexing
- Misapplying DP to linked list traversal
Solution
Step 1: Identify recursion depth
Recursion visits each node once, so recursion stack depth is n.Step 2: Analyze space usage
No extra arrays or data structures are used, but recursion stack frames consume O(n) space.Final Answer:
Option A -> Option AQuick Check:
Recursion stack space grows linearly with list length [OK]
- Assuming constant space for recursion
- Confusing recursion with iterative approach
- Thinking recursion depth is logarithmic
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 requirement for unique values
Duplicates must be skipped, and only M unique smallest values returned.Step 2: Modify min-heap approach
Maintain a hash set to track seen values; when popping from heap, skip if duplicate; stop after M unique values.Step 3: Why other options fail
Stopping after M nodes ignores duplicates; merging all nodes wastes time and space; sequential merges are inefficient.Final Answer:
Option A -> Option AQuick Check:
Hash set + min-heap ensures unique sorted extraction efficiently [OK]
- Stopping after M nodes without filtering duplicates
- Sorting all nodes wastes time
- Sequential merges inefficient for large k
