/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(10, ListNode(20, ListNode(30, ListNode(40)))) k = 3

Output: ListNode(10, ListNode(30, ListNode(40)))

Explanation: The 3rd node from the end is 20. After removal: [10,30,40].

Example 2

Input: head = ListNode(5) k = 1

Output: None

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

Example 3

Input: head = ListNode(7, ListNode(8)) k = 2

Output: ListNode(8)

Explanation: The 2nd node from the end is 7. After removal: [8].

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(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6)))))) k = 4

Expected: ListNode(1, ListNode(2, ListNode(4, ListNode(5, ListNode(6)))))

Case 2

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

Expected: ListNode(9, ListNode(8))

Case 3

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

Expected: ListNode(100, ListNode(300))