Python 1286.py
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.abc = combinations(list(characters), combinationLength) # generator
self.size = math.comb(len(characters), combinationLength)
def next(self) -> str:
self.size -= 1
return "".join(next(self.abc))
def hasNext(self) -> bool:
return self.size > 0
Difficulty
and has an acceptance rate of about 73% (100k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Design
- Iterator
- String
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 CombinationIterator class provides an iterator over all lexicographically ordered combinations of a given length drawn from a string of distinct characters. It relies on Python’s standard library to generate combinations lazily and to compute the total number of possible combinations up front. The public interface consists of two methods, next and hasNext, which together enable sequential access without exposing the underlying generator.
Initialization
During construction the class prepares two essential pieces of state:
def __init__(self, characters: str, combinationLength: int):
self.abc = combinations(list(characters), combinationLength) # generator
self.size = math.comb(len(characters), combinationLength)
-
self.abcholds a generator produced byitertools.combinations. Converting the input string to a list preserves the original order, ensuring that the generated tuples follow the lexical order of the characters. Because a generator is used, the iterator does not materialize the full combination space; each combination is produced only when requested. -
self.sizestores the exact count of combinations, calculated withmath.comb. This pre-computed count enables constant-time checks for remaining elements and eliminates the need to query the generator’s state.
Retrieving the Next Combination
The next method advances the iterator and returns the current combination as a string:
def next(self) -> str:
self.size -= 1
return "".join(next(self.abc))
The method first decrements the remaining count, reflecting that one combination has been consumed. It then calls next on the generator to obtain the next tuple of characters and joins them into a single string. The use of join guarantees that the result matches the expected output format without additional processing.
Checking Availability
The hasNext method reports whether further combinations are available:
def hasNext(self) -> bool:
return self.size > 0
By comparing the stored counter against zero, the method provides an O(1) answer. This design avoids peeking into the generator, which could raise StopIteration and incur unnecessary exception handling overhead.
Edge Cases Handled
The implementation gracefully accommodates several boundary conditions:
-
Zero-length combinations - When
combinationLengthis zero,itertools.combinationsyields a single empty tuple.math.combcorrectly returns 1, sohasNextinitially reports true, andnextreturns an empty string after joining the empty tuple. -
Empty character set - If
charactersis an empty string andcombinationLengthis also zero, the same empty-tuple behavior occurs. For any positivecombinationLength,math.combyields zero, causinghasNextto be false from the start, and the generator would produce no items, preventing accidental iteration. -
Maximum-size request - When
combinationLengthequals the length ofcharacters, the generator yields exactly one tuple containing all characters. The counter reflects this single element, and the iterator correctly reports exhaustion after one call tonext. -
Repeated calls after exhaustion - Because
hasNextchecks the pre-computed counter, oncesizereaches zero the method returns false, and subsequent calls tonextare avoided by the caller. The internal counter prevents underflow, ensuring that the iterator’s state remains consistent.
Performance Optimizations
The code exhibits several deliberate choices that enhance runtime efficiency:
-
Lazy generation - By storing a generator rather than a list of all combinations, memory consumption stays proportional to the length of a single combination rather than the combinatorial explosion of the full set. This is especially beneficial when the number of possible combinations is large.
-
Pre-computed size - Maintaining
self.sizeeliminates the need to query the generator for remaining elements. ThehasNextmethod therefore runs in constant time without invoking any potentially expensive operations on the iterator. -
In-place counter update - Decrementing
self.sizedirectly insidenextavoids an extra method call or separate bookkeeping step. The counter update and element retrieval happen together, keeping the critical path tight. -
Direct string construction - Using
"".joinon the tuple returned by the generator converts the combination to the final string in a single pass, avoiding intermediate list constructions or concatenations.
Overall, the design balances clarity with efficiency, leveraging built-in library functions to handle combinatorial logic while keeping the iterator’s footprint minimal.
ELI5 - Simplified Explanation
Imagine having a big bag filled with alphabet blocks. This code is like a little robot helper that knows how to make every possible group of letters from that bag.
When the robot first wakes up, it looks at the letters you gave it and figures out all the different ways to pick a specific number of them. Think of this like planning all the secret codes you can make with your blocks. The robot keeps these combinations organized in a list inside its memory.
The part called next asks the robot to show the very next secret code it found. Every time it shows one, it remembers to count how many are left. It keeps track of this count so it knows exactly when it has finished showing every single code.
Finally, the part called hasNext is like a simple switch the robot uses to wave at you. If the count of secret codes is still higher than zero, it flashes a light to say that more codes are waiting to be seen. If the count reaches zero, the light stays off because the bag is empty and no more choices are left.
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 | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | Python | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| XiaotaoGuo | C++ | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | Python | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| XiaotaoGuo | C++ | |||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 464: Can I Win
- problem 729: My Calendar I
- problem 1348: Tweet Counts Per Frequency
- problem 1387: Sort Integers by The Power Value
- problem 2424: Longest Uploaded Prefix
- problem 327: Count of Range Sum
- problem 699: Falling Squares
- problem 1553: Minimum Number of Days to Eat N Oranges
- problem 1611: Minimum One Bit Operations to Make Integers Zero
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