You are given an integer n
, the number of teams in a tournament that operates as follows:
n / 2
matches with n / 2
winners advancing to the next round.n - 1
teams are paired to play ((n - 1) / 2)
matches, with ((n - 1) / 2) + 1
winners advancing to the next round.Return the number of matches played in the tournament until a winner is decided.
n
be zero or one? (Typically, it’s at least 1 from the problem’s context).Assuming that n
is at least 1 as per the problem’s context.
We can simulate the process round by round until we are left with one team. In each round:
(n - 1) / 2
.Repeat these steps and keep a count of the total matches until there’s only one team left.
The time complexity of this approach is O(log n)
. Each iteration reduces the number of teams approximately by half, leading to a logarithmic number of iterations.
def numberOfMatches(n: int) -> int:
# Initialize the number of matches to 0
total_matches = 0
# Continue until one team is left
while n > 1:
if n % 2 == 0:
matches = n // 2
n = n // 2
else:
matches = (n - 1) // 2
n = (n - 1) // 2 + 1
total_matches += matches
return total_matches
# Example usage
print(numberOfMatches(7)) # Output: 6
print(numberOfMatches(14)) # Output: 13
In this implementation, we initialize the total number of matches to zero and simulate each round of the tournament until there is only one team remaining. We check if the current number of teams is even or odd, update the number of matches and teams accordingly, and accumulate the count of matches played.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?