Problem 1688

Abstract / Summary

A single elimination tournament with n teams needs n minus one matches to determine a winner.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1688.py

class Solution:
    def numberOfMatches(self, n: int) -> int:
        return 0 if n < 2 else n // 2 + self.numberOfMatches(n - (n // 2))
3 lines | 140 bytes | submitted December 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.96 | σ = 1.57

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
29 links | 17 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   December 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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