Delete N Nodes After M Nodes of a Linked List Problem
#1474
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1474.
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
mnodes starting with the current node. - Remove the next
nnodes - 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.
Example 1:

Input: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
Output: [1,2,6,7,11,12]
Explanation: Keep the first (m = 2) nodes starting from the head of the linked List (1 ->2) show in black nodes.
Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes.
Continue with the same procedure until reaching the tail of the Linked List.
Head of the linked list after removing nodes is returned.
Example 2:

Input: head = [1,2,3,4,5,6,7,8,9,10,11], m = 1, n = 3
Output: [1,5,9]
Explanation: Head of linked list after removing nodes is returned.
Constraints:
- The number of nodes in the list is in the range
[1, 10^4]. 1 <= Node.val <= 10^61 <= m, n <= 1000
Follow up: Could you solve this problem by modifying the list in-place?
Solution
Approach: Keep m, Skip n, Relink in Place
Work in rounds, with a pointer lastKept that starts at the head (the first node of the first round):
- Move
lastKeptforwardm - 1times, so it stands on the m-th node of the round. All of these nodes stay. If the list ends on the way, we are done. - Starting from
lastKept.next, step over the nextnnodes, stopping early if the list runs out. Call the node after themafter(it may benull). - Link
lastKept.next = after, which removes thennodes in one step, and start the next round atafter.
The head is always kept because m >= 1, so we can return the original head. The edge case is a list that ends in the middle of a round, during either the keeping or the skipping: both loops stop at null.
Complexity: O(L) time for a list of L nodes, and O(1) extra space, since the list is changed in place.
class Solution:
def deleteNodes(self, head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]:
last_kept = head
while last_kept is not None:
# walk to the m-th node of this round; it stays
for _ in range(m - 1):
if last_kept.next is None:
return head
last_kept = last_kept.next
# skip the next n nodes (fewer if the list ends) and relink around them
after = last_kept.next
for _ in range(n):
if after is None:
break
after = after.next
last_kept.next = after
last_kept = after # the next round starts here
return head