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:

  1. Start from the head of the linked list
  2. Keep the first m nodes
  3. Remove the next n nodes
  4. 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
๐Ÿš‚ Train Car Management PatternCar 1โœ“ KeepCar 2โœ“ KeepCar 3โœ— RemoveCar 4โœ— RemoveCar 5โœ— RemoveCar 6โœ“ KeepCar 7โœ“ KeepSkip n=3 carsPattern: Keep m=2, Delete n=3, RepeatFinal Train: Car 1 โ†’ Car 2 โ†’ Car 6 โ†’ Car 7Result: [1, 2, 6, 7]Legend:Keep (Passenger Cars)Remove (Maintenance)
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.
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 5
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen