1474. Delete N Nodes After M Nodes of a Linked List - Explanation

Problem Link

Description

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 m nodes starting with the current node.
  • Remove the next n nodes
  • 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⁴].
  • 1 <= Node.val <= 10⁵
  • 1 <= m, n <= 1000

Follow up: Could you solve this problem by modifying the list in-place?


Company Tags


1. Traverse Linked List and Delete In Place

class Solution:
    def deleteNodes(self, head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]:
        current_node = head
        last_m_node = head
        
        while current_node is not None:
            # initialize m_count to m and n_count to n
            m_count, n_count = m, n
            
            # traverse m nodes
            while current_node is not None and m_count != 0:
                last_m_node = current_node
                current_node = current_node.next
                m_count -= 1
            
            # traverse n nodes
            while current_node is not None and n_count != 0:
                current_node = current_node.next
                n_count -= 1
            
            # delete n nodes
            last_m_node.next = current_node
        
        return head

Time & Space Complexity

  • Time complexity: O(N)O(N)
  • Space complexity: O(1)O(1)

Where NN is the length of the linked list pointed by head.