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:
Total number of matches = 3 + 2 + 1 = 6.
Example 2:
Input: n = 14 Output: 13 Explanation: Details of the tournament:
Total number of matches = 7 + 3 + 2 + 1 = 13.
Constraints:
1 <= n <= 200
class Solution {
public int numberOfMatches(int n) {
int 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;
}
}
The most straightforward approach is to simulate the tournament round by round, keeping track of the number of matches played and the number of teams advancing to the next round until only one team remains. This is exactly what the problem description suggests.
class Solution {
public int numberOfMatches(int n) {
int totalMatches = 0;
while (n > 1) {
if (n % 2 == 0) {
totalMatches += n / 2;
n = n / 2;
} else {
totalMatches += (n - 1) / 2;
n = (n - 1) / 2 + 1;
}
}
return totalMatches;
}
}
A more efficient approach is to realize that every team except the winner must lose exactly one match. Therefore, the total number of matches played is simply the number of teams minus one.
class Solution {
public int numberOfMatches(int n) {
return n - 1;
}
}
while
loop iterates until n
becomes 1. In each iteration, n
is roughly halved. Therefore, the number of iterations is logarithmic with base 2, i.e., O(log n).n - 1
. This is a constant-time operation, so the time complexity is O(1).n
. Only a few integer variables are used.Both the naive and optimal solutions effectively cover all edge cases. The optimal solution, however, stands out due to its simplicity and efficiency, reflected in its O(1) time complexity. This makes it superior in terms of performance, especially when dealing with a large number of teams.