ORIGINAL CODING QUESTION
Middle of a mentor chain
Mentors are linked in a chain: each node stores a mentor rating and the index of the next node. The chain order is the order reached from head by following next, which can differ from index order. Return the rating stored in the middle node of the chain. When the chain has an even number of nodes, use the second of the two middle nodes.
Original exercise · easy. Editorial role relevance does not imply a company has asked this question.
Input and output
n head, then n pairs (value next) describing nodes 0 to n-1 in index order. next is the index of the following node, or -1 for the last node. Print the middle rating.
Constraints
1 ≤ n ≤ 200; values in [-1000, 1000]; following next from head visits every node exactly once and then reaches -1.
Example 1
Input
5 2 10 4 20 -1 30 0 40 1 50 3
Output
50
The chain reads 30, 10, 50, 40, 20, so the middle rating is 50.
Example 2
Input
4 0 7 1 8 2 9 3 6 -1
Output
9
The chain reads 7, 8, 9, 6; the second middle node holds 9.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
Counting the nodes first and walking half way takes two passes.
Hint 2
Move one pointer one step and another two steps at a time from head.
Hint 3
Stop when the fast pointer is the last node or has fallen off the end; the slow pointer then sits on the required middle.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →