Menu
CoddyTech

Remove Nth Node From End of List

You get a singly linked list stored in two arrays of the same length. Node i holds the value values[i] and links to node next[i], -1 ends the list, and the head is node 0. The nodes are not stored in list order, so follow the links.

Remove the n-th node counting from the end of the list, where the last node is the 1st from the end. Return the values of the nodes that remain, in list order.

Function

removeNthFromEnd(values: integer-array, next: integer-array, n: integer) → integer-array
valuesinteger-array
the value held by each node
nextinteger-array
the index of the node each node links to, or -1 for the last node
ninteger
which node to remove, counting from the end, where 1 is the last node
Returnsinteger-array
the remaining values in list order, empty when the only node is removed

Constraints

  • 1 ≤ L ≤ 5000, where L is the length of values and of next.
  • -100 ≤ values[i] ≤ 100
  • 1 ≤ n ≤ L
  • Each next[i] is -1 or a node index from 0 to L-1.
  • Starting at node 0, the list visits every node exactly once and then reaches -1. There is no cycle.

Examples

Input
values = [5, 9, 2, 7, 6]next = [2, 3, 4, -1, 1]n = 2
Output
[5, 2, 6, 7]
Explanation
Following the links from node 0 visits nodes 0, 2, 4, 1, 3, so the list reads 5, 2, 6, 9, 7. The 2nd from the end is node 1, value 9, and without it the list reads 5, 2, 6, 7. The array entry values[5-2] = 7 is the last node, not the one to remove.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Can you find and unlink the node in a single pass, without counting the length first?

Reset code
def removeNthFromEnd(values, next, n):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

values = [5, 9, 2, 7, 6]
next = [2, 3, 4, -1, 1]
n = 2

Expected

[5, 2, 6, 7]