Practice
Solution
Step 1: Trace slow and fast pointers
Initial: slow=1, fast=1; Iteration 1: slow=2, fast=3; Iteration 2: fast.next is null, loop ends.Step 2: Return slow's value
Slow points to node with value 3 at loop end.Final Answer:
Option B -> Option BQuick Check:
For even length, returns second middle node (3) [OK]
- Returning first middle node for even length
- Off-by-one errors in loop condition
- Confusing slow and fast pointer positions
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: Identify loop behavior
The algorithm traverses the list once, moving forward by skipping M nodes and deleting N nodes repeatedly.Step 2: Analyze complexity
Since M and N are constants, each iteration moves forward by at least M+N nodes, so total steps proportional to n.Final Answer:
Option A -> Option AQuick Check:
Single pass traversal yields O(n) time complexity [OK]
- Mistaking nested loops causing O(n*(M+N))
- Assuming quadratic due to inner loops
- Ignoring that M and N are constants
Solution
Step 1: Understand new problem constraints
Zero jumps are allowed and single-element loops are valid cycles.Step 2: Identify necessary algorithm change
The original code breaks when slow == next_index(slow) to exclude single-element loops; removing this check allows detecting single-element cycles.Step 3: Confirm direction and zero handling
Zeros represent no movement; allowing them means direction check must still be consistent, but zero jumps can form valid cycles.Final Answer:
Option A -> Option AQuick Check:
Removing single-element loop break correctly detects new valid cycles [OK]
- Skipping zeros entirely
- Treating zero as both directions
- Ignoring direction consistency
Solution
Step 1: Detect cycle length
In a circular list, length is unknown; traverse until returning to start to find length.Step 2: Use two pointers with known length
Once length is known, use two pointers with gapn+1to remove the target node safely.Final Answer:
Option A -> Option AQuick Check:
Cycle length detection is necessary before removal [OK]
- Applying recursion blindly on circular list causing infinite recursion
- Breaking cycle without restoring it, altering list structure
- Using hash sets unnecessarily increasing space
