Magicsheet logo

Find the Winner of an Array Game

Medium
100%
Updated 6/1/2025

Find the Winner of an Array Game

1. What is this problem about?

The Find the Winner of an Array Game interview question is a competition simulation. You have an array of unique integers and a target kk. In each round, the first two elements of the array compete. The larger one "wins" and stays at index 0, while the smaller one moves to the end of the array. The game ends when a number wins kk times in a row. You need to return that winner.

2. Why is this asked in interviews?

Companies like Microsoft and Nvidia ask the Find the Winner coding problem to see if you can optimize a simulation. While you could use a Deque to rotate the array, for large kk, this is sub-optimal. The goal is to realize that you only need one pass through the array. It evaluates your knowledge of Simulation interview patterns and greedy logic.

3. Algorithmic pattern used

This problem is solved using a Single-pass Simulation.

  • Current Leader: Assume the element at index 0 is the current winner.
  • Counter: Keep track of how many consecutive wins the leader has.
  • Iteration: Iterate through the array starting from index 1.
    • If leader > nums[i], increment win_count.
    • If leader < nums[i], the new leader is nums[i] and win_count resets to 1.
  • Termination:
    • If win_count == k, return the leader.
    • If you reach the end of the array, the leader is the global maximum. Since all other numbers have been moved to the end, the global max will win every subsequent round.

4. Example explanation

Array: [2, 1, 3, 5, 4, 6, 7], k=2k = 2

  1. Leader: 2.
  2. 2 vs 1: 2 wins. win_count = 1.
  3. 2 vs 3: 3 wins. leader = 3, win_count = 1.
  4. 3 vs 5: 5 wins. leader = 5, win_count = 1.
  5. 5 vs 4: 5 wins. win_count = 2.
  6. win_count == k. Result: 5.

5. Common mistakes candidates make

  • Actually rotating the array: Using O(KN)O(K \cdot N) if kk is large, which leads to Time Limit Exceeded. The optimized solution is O(N)O(N).
  • Ignoring the Global Max: Forgetting that if kk is larger than the number of elements, the maximum value in the array will eventually win.
  • Counter Reset: Forgetting to reset the win counter when the leader changes.

6. Interview preparation tip

Always look for the "breaking point" in simulation problems. If an operation repeats, ask yourself: "What happens if this goes on forever?" Usually, the largest or smallest element will take control, simplifying the logic.

Similar Questions