/19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

Medium
Linked Lists51.1% acceptance

Given the head node of a singly linked list and an integer k, remove the k-th node from the end of the list and return the head node of the modified list. The linked list is represented by nodes with integer values. If the list becomes empty after removal, return None.

Example 1

Input: head = ListNode(7, ListNode(8, ListNode(9, ListNode(10)))) k = 3

Output: ListNode(7, ListNode(9, ListNode(10)))

Explanation: Removing the 3rd node from the end (value 8) results in [7,9,10].

Example 2

Input: head = ListNode(42) k = 1

Output: None

Explanation: Removing the only node results in an empty list.

Example 3

Input: head = ListNode(1, ListNode(2, ListNode(3))) k = 1

Output: ListNode(1, ListNode(2))

Explanation: Removing the last node (value 3) results in [1,2].

Constraints

  • 1 <= number of nodes in the list <= 30
  • 0 <= node value <= 100
  • 1 <= k <= number of nodes in the list
Python (current runtime)

Case 1

Input: head = ListNode(5, ListNode(6, ListNode(7, ListNode(8, ListNode(9))))) k = 4

Expected: ListNode(5, ListNode(7, ListNode(8, ListNode(9))))

Case 2

Input: head = ListNode(100, ListNode(200)) k = 2

Expected: ListNode(200)

Case 3

Input: head = ListNode(3, ListNode(4, ListNode(5, ListNode(6)))) k = 1

Expected: ListNode(3, ListNode(4, ListNode(5)))