Python 1688.py
class Solution:
def numberOfMatches(self, n: int) -> int:
return 0 if n < 2 else n // 2 + self.numberOfMatches(n - (n // 2))
Difficulty
and has an acceptance rate of about 86% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method numberOfMatches. The method computes the total number of matches required in a knockout tournament given an initial number of participants n. The logic is expressed recursively, handling the base condition directly and delegating the remainder of the computation to subsequent recursive calls.
Key Steps
The core of the algorithm is a conditional expression that distinguishes between the trivial case of fewer than two participants and the general case where matches can be played.
return 0 if n < 2 else n // 2 + self.numberOfMatches(n - (n // 2))
When n is at least two, the expression n // 2 calculates the number of matches that can be conducted in the current round. Each match eliminates one participant, so the number of survivors after the round is n - (n // 2). The method then recursively invokes itself with this reduced participant count, adding the matches from the current round to the total returned by the recursive call.
The recursion terminates when the participant count drops below two, at which point the method returns zero because no further matches are possible.
Edge Cases
The implementation explicitly handles the scenario where the tournament starts with zero or one participant. In such cases, the conditional n < 2 evaluates to true, and the method returns 0. This correctly reflects that a tournament cannot proceed without at least two competitors.
Another subtle edge case arises when n is odd. Integer division n // 2 yields the floor of half the participants, meaning one participant receives a bye and automatically advances to the next round. The recursive call receives n - (n // 2), which retains this unpaired participant along with the winners of the matches, ensuring the algorithm correctly models the progression of an odd-sized tournament.
Performance Optimizations
The algorithm leverages the mathematical property that each round reduces the participant count by roughly half. By using integer division, the code avoids the overhead of explicit loops and conditionals that would otherwise be required to simulate each round iteratively. This results in a compact representation that naturally limits the depth of recursion to a logarithmic number of calls relative to the initial n.
Because each recursive invocation performs only a constant amount of work-calculating n // 2, a subtraction, and an addition-the overall execution remains efficient. The recursion depth is bounded, preventing excessive stack growth even for large values of n. The use of Python's built-in integer arithmetic ensures that the calculations are performed with minimal overhead.
ELI5 - Simplified Explanation
Imagine there is a big tournament with many teams playing soccer. Every time two teams meet for a game, one team wins and one team loses. The winner keeps playing, but the loser has to go home.
This code acts like an organizer for the tournament. It looks at the number of teams, which is called n. If there is only one team left, the tournament is over because there is nobody else to play against. If there are more teams, the code divides them into pairs. Half of the teams get to play, so the number of matches is equal to half of the teams. Then, the winners join the leftover teams, and the code runs again to count the next round of games. It keeps doing this dance until the very last team is left standing as the winner.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | JS | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| muhammadfarhankt | Go | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2549: Count Distinct Numbers on Board
Solved On The Same Day
- problem 1592: Rearrange Spaces Between Words
- problem 2873: Maximum Value of an Ordered Triplet I
- problem 2937: Make Three Strings Equal
- problem 2434: Using a Robot to Print the Lexicographically Smallest String
- problem 2516: Take K of Each Character From Left and Right
- problem 2610: Convert an Array Into a 2D Array With Conditions
- problem 2671: Frequency Tracker
- problem 2711: Difference of Number of Distinct Values on Diagonals
- problem 2766: Relocate Marbles
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality