Skills101
← All coding problems

Remove Nth Node From End of List

mediumLinked List+20 XPTime limit 2s

Remove the k-th node from the end of the list (k = 1 is the tail) and print the list.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: one list, then a third line k.

Output: the list after removing that node (empty if nothing is left).

Constraints: 1 ≤ n ≤ 10⁵, 1 ≤ k ≤ n.

Challenge — one pass: move a fast pointer k steps ahead, then move fast and slow together until fast hits the end. A dummy node before the head handles removing the head itself.

Sample input 1

5
1 2 3 4 5
2

Sample output 1

1 2 3 5

Sample input 2

1
1
1

Sample output 2

empty

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.