linked list December 19, 2022

Delete n nodes after m nodes of a linked list

Time O(n) Space O(1) Open original problem

We will create a dummy node and attach the head node to it. Then we will do the following:

  • Use an indicator i to count the number of already-passed list nodes
  • Keep moving head node forward as long as i < m-1
  • Remove the next n nodes and reset i to 0 when i == m-1
class Solution:
    def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode:
        dummy = ListNode(0, head)
        i = 0
        while head:
            if i < m-1:
                i += 1
            elif i == m-1:
                for _ in range(n):
                    if head.next:
                        head.next = head.next.next
                i = 0
            head = head.next
        return dummy.next

Time complexity: O(n)
Space complexity: O(1)