Closed Tram Stop

Mediumtwo pointersAlso known as Remove Nth Node From End of List

A tram line's route is stored as a chain of stops, from the first stop to the terminus. Each stop only knows the next stop on the line.

Roadworks close a stop, and the notice from the city counts from the far end: "the 3rd stop before the end of the line, counting the terminus as 1st". The route system must skip that stop. It reads the route once, from the front, because the route can be long and is shared with other systems.

Your task

Write closeStop(head, k). Remove the k-th node counting from the end of the list (k = 1 is the last node) and return the head of the updated list.

If the removed stop was the first one, the head changes. If it was the only stop, return an empty list (null / None). Try to do it in a single pass.

closeStop(head: ListNode, k: int) → ListNode

Examples

Example 1
Input
head = [11, 24, 35, 47, 52]
k = 2
Output
[11, 24, 35, 52]
Why

Counting from the end, 52 is 1st and 47 is 2nd. Remove 47, so 35 now points straight to 52.

Example 2
Input
head = [11, 24, 35]
k = 3
Output
[24, 35]
Why

The 3rd stop from the end of a 3-stop line is the first stop. There is no stop before it to relink, so the new head is 24.

Constraints

  • 1 ≤ number of stops ≤ 5,000
  • 1 ≤ k ≤ number of stops
  • Stop ids are integers and may repeat.
Start with brute force

Walk the whole route once to count the stops, n. The closed stop is number n - k + 1 counting from the front, so walk again to the stop just before it and relink that one.

That is O(n) and correct, so the problem is not speed in big-O terms. It reads the route twice, though, and the city's system only wants one read. The gap trick does the same job in one pass, and the same idea finds "the k-th last item" of any stream you can read only once.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code