All problems

Problem 113

Remove Nth Node From End

Medium · 20 pts · Linked List, Two Pointers

Problem

You are given a linked list with N nodes and a number K. Remove the K-th node counted from the end of the list (K = 1 is the last node, K = N is the head) and print the resulting list. Try to do it in a single pass: move a first pointer K nodes ahead, then move it and a second pointer together until the first one reaches the end. The second pointer is then just before the node to remove. A dummy node in front of the head makes removing the head itself easy.

Input

First line: integers N and K. Second line: the N node values from head to tail.

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

1 <= K <= N <= 100000; -1000 <= value <= 1000

Example input

5 2
1 2 3 4 5

Example output

1 2 3 5

Explanation

In 1 2 3 4 5 with K = 2, counting from the end gives 5 as the 1st and 4 as the 2nd node. Removing 4 leaves 1 2 3 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Middle of the Linked List Next: Merge Two Sorted Lists