You are given a positive integer n
which denotes the number of teams in a competition. Each team is given a unique number from 1 to n. In each round, two teams compete against each other, and the winning team moves to the next round. There are n-1
rounds in total. After the final round, there is one winning team—the champion.
You need to find and return the number of the champion team using the following rule:
Example:
n = 4
4
n
always an even number?
n
will be an even number as each team with the same parity will have a matching opponent.The problem essentially boils down to progressively reducing the number of teams by half in each round, and then moving the winners to the next round until one team (the champion) remains. An efficient way to simulate this process without keeping track of the individual matchups is to keep reducing the number of teams by half until we are left with one team.
n
).def findChampion(n: int) -> int:
# The final winner after reducing the number of teams by half each round
while n != 1:
n = n // 2
return n
# Example usage:
print(findChampion(4)) # Output: 1
print(findChampion(16)) # Output: 1
n
.This provides an efficient way to determine the champion team number without explicitly simulating every single match.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?