You are given an integer n, the number of teams in a tournament that has strange rules:
- If the current number of teams is even, each team gets paired with another team. A total of
n / 2matches are played, andn / 2teams advance to the next round. - If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of
(n - 1) / 2matches are played, and(n - 1) / 2 + 1teams advance to the next round.
Return the number of matches played in the tournament until a winner is decided.
Constraints:
1 <= n <= 200
Approach: Simulation
func numberOfMatches(n int) int {
ans := 0
for n > 1 {
ans += n / 2
if n%2 == 0 {
n = n / 2
} else {
n = n/2 + 1
}
}
return ans
}Intuition
The problem simulates a knockout tournament where, in each round, teams are paired to play matches. Every match eliminates one team. If there's an odd number of teams, one team gets a bye (automatically advances). This process continues until only one team remains.
Algorithm
-
Initialize:
Set a counteransto track the total number of matches played. -
Iterate Through Rounds:
- While more than one team remains (
n > 1):- Calculate the number of matches in the current round as
n / 2and add it toans. - Update the number of teams for the next round:
- If
nis even, all teams are paired, so next round hasn / 2teams. - If
nis odd, one team gets a bye, so next round hasn / 2 + 1teams.
- If
- Calculate the number of matches in the current round as
- While more than one team remains (
-
Return the Result:
Once the loop finishes,anscontains the total number of matches played.
Complexity Analysis
-
Time Complexity:
O(log n)
Each round roughly halves the number of teams, leading to a logarithmic number of iterations. -
Space Complexity:
O(1)
The algorithm uses only a constant amount of extra space.
Wrap up
If you found this guide helpful, consider subscribing to my newsletter on jyotirmoy.dev/blogs , You can also follow me on Twitter jyotirmoydotdev for updates and more content.

