Hey everyone!
This is our second article in the DSA learning series where we aim to grow together — one problem at a time.
Our goal remains the same: to make concepts simpler, logic clearer, and learning collaborative.
Problem Statement
In this problem we are given a linked list, and we have to perform the following operations:
Keep M nodes, then delete N nodes, and keep repeating this until the end of the list.
Example:
Input:
Linked List: 9 → 1 → 3 → 5 → 9 → 4 → 10 → 1
M = 2, N = 1
Output:
9 → 1 → 5 → 9 → 10 → 1
Explanation:
Skip 2 nodes (9, 1), delete the next 1 (3), then skip 2 again (5, 9), delete next (4), and continue.
Thought Process
This is one of those pointer problems where clarity beats complexity.
We can solve this cleanly using just one loop — by breaking the task into repeatable chunks:
Skip M nodes — these are the nodes we keep.
Delete N nodes — we move a second pointer ahead by N, cutting them out of the chain.
Connect the last kept node to the node after the deleted segment.
Repeat until the list ends.
This approach is iterative, clean, and runs in O(length of list).
Code Implementation
static void linkdelete(Node head, int m, int n) {
Node temp = head;
while (temp != null) {
// Skip M nodes (we are already on the 1st one)
int countM = 1;
while (countM < m && temp != null) {
temp = temp.next;
countM++;
}
// If we reached the end, nothing to delete
if (temp == null) return;
// Start deleting next N nodes
Node sampleTemp = temp.next;
int countN = 1;
while (countN <= n && sampleTemp != null) {
sampleTemp = sampleTemp.next;
countN++;
}
// Connect Mth node to the node after deleted segment
temp.next = sampleTemp;
// Move temp to the next segment
temp = sampleTemp;
}
}
⚙️ Time and Space Complexity
| Type | Complexity | Explanation |
|---|---|---|
| Time | O(L) | We traverse each node once |
| Space | O(1) | Only pointers and counters used |
Wrapping Up
This problem is a great exercise in pointer control and in-place modification.
We hope our explanation helped you connect the logic step by step and see how iterative thinking simplifies complex pointer tasks.
💬 We’d love your support!
Share your feedback, ask questions, and let’s keep learning together — one DSA problem at a time.
DSA Series by Broken Compilers.
Follow our journey as we learn, teach, and grow through code.
Top comments (0)