Given a linked list and two positive integers, m and n, delete every n nodes after skipping m nodes.

For example, consider the following list:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
 
If m = 1, n = 3
 
1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
1 —> 5 —> 9 —> null
 
 
If m = 2, n = 2
 
1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> null
1 —> 2 —> 5 —> 6 —> 9 —> 10 —> null

Practice this problem

The idea is to traverse the given list, skip the first m nodes, delete the next n nodes, and recur for the remaining nodes. The solution is simple, but we need to ensure that all boundary conditions are handled properly in the code.

The implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 5 —> 9 —> NULL

Java


Download  Run Code

Output:

1 —> 5 —> 9 —> null

Python


Download  Run Code

Output:

1 —> 5 —> 9 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.