Linked lists · Problem 3 of 3

Remove the k-th booking from the end

Pattern: Remove Nth Node From End of a List

mediumNot solved yet

The problem

Bookings are stored as a linked list in the order they were made. Write a function that removes the booking that is k-th from the end (k = 1 is the last one) and returns the head of the updated list. You can assume 1 <= k <= length of the list.

Try to do it in one pass over the list.

text
1remove_kth_from_end([10, 20, 30, 40, 50], 2)  ->  [10, 20, 30, 50]
2remove_kth_from_end([10, 20, 30], 3)          ->  [20, 30]
3remove_kth_from_end([10], 1)                  ->  []
Example 1, k = 2
10
20
30
40
50
null

40 is 2nd from the end: 30 links straight to 50.

Write remove_kth_from_end(head, k) in Python or removeKthFromEnd(head, k) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 18 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.