Find Final Ball Holder
Company: Hackerrank
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of functional graphs, cycle detection, and handling large-step transitions in deterministic mappings where repeated state updates occur.
Constraints
- 1 <= n == len(receiver) <= 2 * 10^5
- 1 <= receiver[i] <= n
- 0 <= k <= 10^18
- Each friend passes the ball to exactly one friend
Examples
Input: ([2, 4, 5, 3, 1], 6)
Expected Output: 2
Explanation: The path is 1 -> 2 -> 4 -> 3 -> 5 -> 1 -> 2, so after 6 seconds friend 2 has the ball.
Input: ([1], 0)
Expected Output: 1
Explanation: At time 0, friend 1 already has the ball.
Input: ([2, 3, 4, 5, 3], 10)
Expected Output: 5
Explanation: The path is 1 -> 2 -> 3 -> 4 -> 5 -> 3 -> 4 -> 5 -> 3 -> 4 -> 5. After 10 seconds the ball is at friend 5.
Input: ([2, 1, 4, 3], 1000000000001)
Expected Output: 2
Explanation: Starting from friend 1, the ball alternates between 1 and 2. Since k is odd, friend 2 holds the ball.
Input: ([2, 3, 3], 100)
Expected Output: 3
Explanation: The path is 1 -> 2 -> 3, and then friend 3 keeps the ball forever because receiver[2] = 3.
Hints
- If you record the first time each friend is visited, you can detect when the ball movement starts repeating.
- Once you find a cycle, you do not need to simulate all remaining seconds; use modular arithmetic to jump to the final position.