Delete N Nodes After M Nodes of a Linked List - Problem

You are given the head of a linked list and two integers m and n.

Traverse the linked list and remove some nodes in the following way:

  • Start with the head as the current node.
  • Keep the first m nodes starting with the current node.
  • Remove the next n nodes
  • Keep repeating steps 2 and 3 until you reach the end of the list.

Return the head of the modified list after removing the mentioned nodes.

Input & Output

Example 1 — Basic Pattern
$ Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 2, n = 3
Output: [1,2,6,7,11]
💡 Note: Keep first 2 nodes (1,2), delete next 3 (3,4,5), keep next 2 (6,7), delete next 3 (8,9,10), keep remaining (11)
Example 2 — Short List
$ Input: head = [1,2,3,4], m = 1, n = 2
Output: [1,4]
💡 Note: Keep 1 node (1), delete next 2 (2,3), keep remaining (4)
Example 3 — Delete All After Keep
$ Input: head = [1,2,3], m = 1, n = 3
Output: [1]
💡 Note: Keep 1 node (1), delete next 3 but only 2,3 exist, so final result is [1]

Constraints

  • The number of nodes in the given linked list is in the range [1, 104].
  • 1 ≤ Node.val ≤ 106
  • 1 ≤ m, n ≤ 1000

Visualization

Tap to expand
Delete N Nodes After M Nodes INPUT Linked List (11 nodes): 1 2 3 4 5 6 7 8 9 10 11 NULL Parameters: m = 2 (nodes to KEEP) n = 3 (nodes to DELETE) Input Array: [1,2,3,4,5,6,7,8,9,10,11] ALGORITHM STEPS (Chunk Processing) 1 Keep m=2 nodes Traverse and keep [1,2] 1 2 2 Delete n=3 nodes Skip/remove [3,4,5] 3 4 5 X 3 Repeat: Keep [6,7] Delete [8,9,10] 6 7 8 9 10 4 Final: Keep [10,11] End of list reached 10 11 Keep Delete FINAL RESULT Modified Linked List: 1 2 6 7 10 11 NULL Output Array: [1, 2, 6, 7, 10, 11] Summary: Original nodes: 11 Nodes kept: 6 Nodes deleted: 5 (3+0+0) OK - Complete Key Insight: Chunk Processing processes nodes in groups of (m + n). For each chunk, we keep the first m nodes and skip the next n nodes. This approach requires only a single pass through the list with O(n) time complexity and O(1) space, making it optimal for this problem. TutorialsPoint - Delete N Nodes After M Nodes of a Linked List | Chunk Processing Approach
Asked in
Microsoft 15 Amazon 12 Facebook 8 Google 6
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