← HackerRank Interview Insights
My first instinct was just simulate it, which works fine until you see k can be something like a billion.
Model the ball passing as a functional graph where each node has exactly one outgoing edge. Since k can be very large, use cycle detection (e.g., Floyd's algorithm) to find the cycle length and reduce k modulo the cycle length after accounting for the tail. Then simulate the remaining steps to find the final holder.
Pro tip: Always clarify constraints first: if n is small (e.g., ≤ 10^5) and k is huge, cycle detection is optimal; if n is also huge, you might need a different approach. Mentioning this shows you consider scalability.
Restate the problem: starting from friend 1, after each second the ball moves to receiver[i]. We need the friend after exactly k seconds. Note that k can be very large, so simulation is infeasible.
Each friend has exactly one outgoing edge to receiver[i]. This forms a directed graph where each component has exactly one cycle with trees feeding into it. The ball's path will eventually enter a cycle.
Use Floyd's cycle-finding algorithm (tortoise and hare) to find the cycle start (tail length) and cycle length. Alternatively, use a visited array to record the first time each node is seen.
If k < tail length, simulate k steps from start. Otherwise, reduce k to (k - tail_length) % cycle_length and then simulate that many steps from the cycle start. Return the resulting friend.
Time O(n) and space O(1) with Floyd's, or O(n) space with visited array. Handle edge cases: k=0 (friend 1), self-loops, and multiple components (though start is always 1).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.