Ninja is in the process of constructing a racecourse, which can be represented as a singly linked list. This list contains ‘N’ checkpoints, each represented as a node, and concludes at the final node.
However, Ninja accidentally connected the final checkpoint of the racecourse to the ‘Kth’ checkpoint (indexed from 0), creating an infinite loop for the racecars.
Your task here is to remove all the checkpoints that are in the loop and print the racecourse after the removal of the loop.
Refer example for better understanding.
Example : N = 4
K = 1
NODE = 1->2->3->4

You can see there is a loop from the ‘1st’ node to the ‘3rd’ node (0 based), so we will remove all nodes from (1 - 3), so the answer is [ 1 ].
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of the test case contains ‘N + 1’ space-separated where the first 'N' elements represent the LinkedList node, and the last integer is always '-1' representing the end of the LinkedList.
The second line contains a single integer ‘K’ denoting the start node of the loop.
Output format :
Print the racecourse after removing loop nodes. It is guaranteed there will be at least one node after removal.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 1e5
0 <= K < N
Sum of N <= 10^5
Time Limit: 1 sec
2
1 4 5 6 7 8 -1
3
4 5 7 6 -1
1
1 4 5
4
For test case 1,
Initially the racecourse looks like,

After removing, 6->7->8 (Nodes in the loop), our final LinkedList looks like this.

For test case 2,
Initially, the racecourse looks like,

After removing, 6->7->8 (Nodes in the loop), our final LinkedList looks like this.

2
1 4 5 6 -1
3
1 3 -1
1
1 4 5
1
Can you create a new final node of the racecourse?
APPROACH :
ALGORITHM :
O(N), where ‘N’ is the size of our linked list ‘HEAD’.
We will iterate over LinkedList only once. Hence, the overall Space Complexity is O(N).
O(1), where O(1) represents constant space.
Constant extra space is required. Hence, the overall Space Complexity is O(1).