Taro Logo

Count of Matches in Tournament

Easy
Amazon logo
Amazon
2 views
Topics:
Greedy Algorithms

You are given an integer n, the number of teams in a tournament with the following rules:

  1. If the number of teams is even, each team gets paired, n / 2 matches are played, and n / 2 teams advance.
  2. If the number of teams is odd, one team advances randomly, (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:

  • If n = 7, the output is 6. The tournament proceeds as follows:
    • Round 1: 7 teams, 3 matches, 4 teams advance.
    • Round 2: 4 teams, 2 matches, 2 teams advance.
    • Round 3: 2 teams, 1 match, 1 team wins. Total matches = 3 + 2 + 1 = 6.
  • If n = 14, the output is 13. The tournament proceeds as follows:
    • Round 1: 14 teams, 7 matches, 7 teams advance.
    • Round 2: 7 teams, 3 matches, 4 teams advance.
    • Round 3: 4 teams, 2 matches, 2 teams advance.
    • Round 4: 2 teams, 1 match, 1 team wins. Total matches = 7 + 3 + 2 + 1 = 13.

How would you solve this problem efficiently, and what is the time and space complexity of your solution?

Solution


Naive Approach

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.

Code

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

Time and Space Complexity

  • Time Complexity: O(log n) because in each iteration, the number of teams is reduced by approximately half.
  • Space Complexity: O(1) as we are only using a constant amount of extra space.

Optimal Approach

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.

Code

def number_of_matches_optimal(n):
    return n - 1

Time and Space Complexity

  • Time Complexity: O(1), as it involves only a single arithmetic operation.
  • Space Complexity: O(1), constant space.

Edge Cases

The constraints specify 1 <= n <= 200. When n = 1, there are no matches. The optimal solution correctly handles this by returning 1 - 1 = 0.

Summary

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.