700297. Remove every k'th node

Easy

Remove every k'th node

Summary

The problem is to remove every kth node from a singly linked list. This involves skipping nodes at intervals of k, effectively removing them from the original list. The key concept involved is manipulating a linked list, specifically removing nodes while traversing the list.

Detailed Explanation

To solve this problem, we'll create a new pointer that moves one step ahead every kth node. As we traverse the original list, we'll keep track of the current node and remove it if it's the kth node. We'll also maintain a reference to the previous node to correctly update the next pointer.

Here's a step-by-step breakdown of the solution:

  1. Initialize three pointers: curr, prev, and kth.
  2. Set kth to 0 and curr to the head of the linked list.
  3. Traverse the linked list:
    • If kth is equal to 0, it means we've reached a node that should be removed.
      • Update prev to point to the current node (curr).
      • Move kth to (kth + 1) % k. This ensures we skip nodes at intervals of k.
    • Otherwise, move curr one step ahead and update kth to (kth + 1) % k.
  4. Repeat steps 3 until the end of the linked list is reached.
  5. Update the next pointer of the last node (prev) to point to NULL, effectively terminating the list.

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a few extra variables to store the pointers and counters.

Optimized Solutions

Java

View on GeeksforGeeks
public class RemoveEveryKthNode {
    public static void removeEveryKthNode(ListNode head, int k) {
        ListNode prev = null;
        ListNode curr = head;
        int count = 0;

        while (curr != null) {
            if ((count + 1) % k == 0) {
                prev = curr;
                curr = curr.next;
                continue;
            }

            prev = curr;
            curr = curr.next;
            count++;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.