Delete N Nodes After M Nodes of a Linked List - Problem
You're given the head of a linked list and two integers m and n.
Your task: Traverse the linked list following a specific pattern - keep m nodes, then delete the next n nodes, and repeat this cycle until you reach the end.
Pattern:
- Start from the head of the linked list
- Keep the first
mnodes - Remove the next
nnodes - Repeat steps 2-3 until you reach the end
Example: If m=2 and n=3, you'll keep 2 nodes, delete 3 nodes, keep 2 nodes, delete 3 nodes, and so on.
Return the head of the modified linked list after all deletions.
Input & Output
example_1.py โ Basic Pattern
$
Input:
head = [1,2,3,4,5,6,7,8,9,10,11], m = 2, n = 3
โบ
Output:
[1,2,6,7,10,11]
๐ก Note:
Keep nodes 1,2 โ Delete nodes 3,4,5 โ Keep nodes 6,7 โ Delete nodes 8,9,10 โ Keep node 11. Note: We only delete 2 nodes (8,9) in the last cycle because node 10 doesn't exist in the delete phase.
example_2.py โ Small List
$
Input:
head = [1,2,3,4,5], m = 1, n = 2
โบ
Output:
[1,4]
๐ก Note:
Keep node 1 โ Delete nodes 2,3 โ Keep node 4 โ Try to delete nodes 5,6 but only node 5 exists so delete it โ Result: [1,4]
example_3.py โ Edge Case
$
Input:
head = [1,2], m = 1, n = 1
โบ
Output:
[1]
๐ก Note:
Keep node 1 โ Delete node 2 โ No more nodes left. Result: [1]
Constraints
-
The number of nodes in the list is in the range
[1, 104] -
1 โค Node.val โค 1000 -
1 โค m, n โค 1000 - Follow up: How would you solve this problem if you needed to minimize memory usage?
Visualization
Tap to expand
Understanding the Visualization
1
Start Journey
Begin at the head of the train (linked list) with your m-keep, n-delete pattern rules
2
Keep Cars
Advance through m cars, keeping them connected for passengers
3
Disconnect Cars
Skip the next n cars by updating the connection to bypass them
4
Repeat Pattern
Continue this keep-delete cycle until you reach the end of the train
Key Takeaway
๐ฏ Key Insight: By maintaining a pointer to the last kept node and efficiently skipping unwanted nodes, we can solve this in a single pass with O(1) extra space, just like a conductor efficiently managing train cars.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code