Closed Tram Stop

Mediumtwo pointersAlso known as Remove Nth Node From End of List

A tram route is stored as a chain of stops from the first stop to the terminus. Each stop knows only the next one.

Roadworks close a stop, and the city's notice 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, reading the long, shared route only once, from the front.

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

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. No stop before it needs relinking, 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 route once to count the stops, n. The closed stop is number n - k + 1 from the front, so walk again to the stop before it and relink.

That is O(n) and correct, but it reads the route twice. The gap trick does it 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