Count of Matches in Tournament

easy math simulation tournament

Problem

A tournament starts with n teams. Each round, if the team count is even they all pair up: n / 2 matches are played and n / 2 teams advance. If the count is odd, one team advances for free and the rest pair up: (n − 1) / 2 matches are played and (n − 1) / 2 + 1 teams advance. Return the total number of matches played until a single winner remains.

Inputn = 7
Output6
7 → 3 matches, 4 advance; 4 → 2 matches, 2 advance; 2 → 1 match, 1 winner. Total = 3 + 2 + 1 = 6.

def numberOfMatches(n):
    matches = 0
    while n > 1:
        if n % 2 == 0:
            matches += n // 2       # all teams pair up
            n //= 2                 # n/2 teams advance
        else:
            matches += (n - 1) // 2  # one team skips, rest pair
            n = (n - 1) // 2 + 1     # winners + the lucky skipper
    return matches
function numberOfMatches(n) {
  let matches = 0;
  while (n > 1) {
    if (n % 2 === 0) {
      matches += n / 2;              // all teams pair up
      n = n / 2;                     // n/2 teams advance
    } else {
      matches += (n - 1) / 2;        // one team skips, rest pair
      n = (n - 1) / 2 + 1;           // winners + the lucky skipper
    }
  }
  return matches;
}
int numberOfMatches(int n) {
    int matches = 0;
    while (n > 1) {
        if (n % 2 == 0) {
            matches += n / 2;            // all teams pair up
            n = n / 2;                   // n/2 teams advance
        } else {
            matches += (n - 1) / 2;      // one team skips, rest pair
            n = (n - 1) / 2 + 1;         // winners + the lucky skipper
        }
    }
    return matches;
}
int numberOfMatches(int n) {
    int matches = 0;
    while (n > 1) {
        if (n % 2 == 0) {
            matches += n / 2;            // all teams pair up
            n = n / 2;                   // n/2 teams advance
        } else {
            matches += (n - 1) / 2;      // one team skips, rest pair
            n = (n - 1) / 2 + 1;         // winners + the lucky skipper
        }
    }
    return matches;
}
Time: O(log n) Space: O(1)