You are given an integer n
, the number of teams in a tournament with the following rules:
n / 2
matches are played, and n / 2
teams advance.(n - 1) / 2
matches are played, and (n - 1) / 2 + 1
teams advance.Return the number of matches played in the tournament until a winner is decided.
For example:
n = 7
, the output is 6. The tournament proceeds as follows:
n = 14
, the output is 13. The tournament proceeds as follows:
How would you solve this problem efficiently, and what is the time and space complexity of your solution?
The most straightforward approach is to simulate the tournament round by round. We can keep track of the number of teams and matches played in each round until we reach a single winner. This involves iteratively applying the rules given in the problem statement until n
becomes 1.
def number_of_matches_naive(n):
matches = 0
while n > 1:
if n % 2 == 0:
matches += n // 2
n = n // 2
else:
matches += (n - 1) // 2
n = (n - 1) // 2 + 1
return matches
An optimal solution can be derived by recognizing a simple invariant. Each match eliminates one team. If we start with n
teams, we need n - 1
matches to be played to arrive at a single winner. Therefore, the total number of matches played will always be n - 1
.
def number_of_matches_optimal(n):
return n - 1
The constraints specify 1 <= n <= 200
. When n = 1
, there are no matches. The optimal solution correctly handles this by returning 1 - 1 = 0
.
The optimal solution is more efficient because it directly calculates the number of matches without simulating the tournament. It leverages the fundamental relationship that the number of matches needed is always one less than the initial number of teams.