Problem 1286

Abstract / Summary

Implement an iterator that generates all possible combinations of a given length from a set of characters.

Note

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

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
11 lines | 402 bytes | submitted September 29, 2023 | GitHub   11% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (100k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Design
  • Iterator
  • String
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 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.abc holds a generator produced by itertools.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.size stores the exact count of combinations, calculated with math.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 combinationLength is zero, itertools.combinations yields a single empty tuple. math.comb correctly returns 1, so hasNext initially reports true, and next returns an empty string after joining the empty tuple.

  • Empty character set - If characters is an empty string and combinationLength is also zero, the same empty-tuple behavior occurs. For any positive combinationLength, math.comb yields zero, causing hasNext to be false from the start, and the generator would produce no items, preventing accidental iteration.

  • Maximum-size request - When combinationLength equals the length of characters, the generator yields exactly one tuple containing all characters. The counter reflects this single element, and the iterator correctly reports exhaustion after one call to next.

  • Repeated calls after exhaustion - Because hasNext checks the pre-computed counter, once size reaches zero the method returns false, and subsequent calls to next are 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.size eliminates the need to query the generator for remaining elements. The hasNext method therefore runs in constant time without invoking any potentially expensive operations on the iterator.

  • In-place counter update - Decrementing self.size directly inside next avoids 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 "".join on 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.

written by openai gpt

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.

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 = 6 | μ = 5.89 | σ = 2.02

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 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
26 links | 18 authors | 7 languages

Videos

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

Solved On The Same Day

10 solutions   September 29, 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