Simulate a tennis tournament by ranks and return the winner's rank.
You are evaluating the match results of a tennis tournament. You are given an array of players where each element is the player's rank. Match the ranks in consecutive pairs starting from index 0, and naively assume the better ranked player wins each match. Repeat until only the winner remains. Log the results of each elimination round and return the rank of the winner. The array length is always a power of 2 and no two ranks are the same.
Example: ranks = [1, 3, 4, 6, 7, 8, 5, 2] gives rounds [1, 4, 7, 2], then [1, 2], then [1], so the winner is 1.
Follow-up 1: Better ranked players may get eliminated early (for ranks = [1, 2, 4, 5], rank 2 is eliminated in round 1). Given an array of ranks, find an ordering that makes better ranks get eliminated as late as possible. For ranks = [1, 3, 4, 6, 7, 8, 5, 2], one optimal ordering is [1, 6, 3, 7, 2, 5, 4, 8], where the best four ranks survive round 1 and the best two survive round 2.
Follow-up 2: How would you adjust your implementation if the length of the ranks array is not a power of 2?
Expect follow-ups like
- Find an ordering of the ranks so that better ranks are eliminated as late as possible.
- How would you adjust the implementation if the length is not a power of 2?
Community answers
Related courses


