Menu
CoddyTech

Middle of the Linked 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.

Return the value of the middle node. When the list has an even number of nodes there are two middle nodes; return the value of the second one.

Function

middleNode(values: integer-array, next: integer-array) → integer
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
Returnsinteger
the value of the middle node, the second middle one when the length is even

Constraints

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

Examples

Input
values = [4, 9, 2, 7, 5]next = [3, -1, 1, 4, 2]
Output
5
Explanation
Following the links from node 0 gives nodes 0, 3, 4, 2, 1, so the list reads 4, 7, 5, 2, 9. The third of the five is node 4, whose value is 5. The array's own middle entry, values[2] = 2, is a different node.

lock icon+13 hidden tests on Submit

challenge icon

Follow-up

Can you return the node one third of the way down the list in a single pass? How fast would each pointer move, and where would you stop?

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

Case 1

Case 2

Case 3

Input

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

Expected

5