You are given an integer n, the number of teams in a tournament that has strange rules:
n / 2 matches are played, and n / 2 teams advance to the next round.(n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.Return the number of matches played in the tournament until a winner is decided.
Example 1:
Input: n = 7 Output: 6 Explanation: Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6.
Example 2:
Input: n = 14 Output: 13 Explanation: Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13.
Constraints:
1 <= n <= 200This approach involves treating the tournament rounds as iterative events where in each round, the number of matches is calculated, and non-advanced teams are eliminated until one team remains. This approach iterates over the number of teams until a winner is decided by subtracting the number of matches played from the total count of teams.
The function numberOfMatches uses a loop to repeatedly determine the number of matches in each round and adjust the number of teams until a single team remains. If the number of teams n is even, n / 2 matches are played. If n is odd, (n - 1) / 2 matches occur, and one team directly advances.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n) since in each step the number of teams is halved.
Space Complexity: O(1) since we only use a constant amount of additional memory.
Instead of simulating each round, this approach uses the observation that to find a winner among n teams, exactly n - 1 matches must be played. This is because each match eliminates exactly one team and n - 1 eliminations leave one champion.
The function numberOfMatches directly returns n - 1 under the logical deduction that each match will remove one team until only one team remains.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Iterative Reduction Approach | Time Complexity: O(log n) since in each step the number of teams is halved. |
| Direct Mathematical Calculation | Time Complexity: O(1) |
Count of Matches in Tournament - Leetcode 1688 - Python • NeetCodeIO • 4,317 views views
Watch 9 more video solutions →Practice Count of Matches in Tournament with our built-in code editor and test cases.
Practice on FleetCode