Iterator for Combination - Problem
Design a CombinationIterator class that generates all combinations of a given length from a sorted string of distinct characters.
Your class should implement:
CombinationIterator(string characters, int combinationLength)- Initializes the object with a string of sorted distinct lowercase English letters and the desired combination length.next()- Returns the next combination of the specified length in lexicographical order.hasNext()- Returnstrueif and only if there exists a next combination.
Note: You may assume that there is always a next combination when next() is called.
Input & Output
Example 1 — Basic Case
$
Input:
operations = ["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"], parameters = [["abc", 2], [], [], [], [], [], []]
›
Output:
[null, "ab", true, "ac", true, "bc", false]
💡 Note:
Create iterator for combinations of length 2 from 'abc'. Returns 'ab', then 'ac', then 'bc'. After 'bc', no more combinations exist.
Example 2 — Single Character Combinations
$
Input:
operations = ["CombinationIterator", "next", "hasNext", "next", "hasNext"], parameters = [["abcd", 1], [], [], [], []]
›
Output:
[null, "a", true, "b", true]
💡 Note:
Iterator for single character combinations from 'abcd'. Returns each character in order: 'a', 'b', etc.
Example 3 — Full Length Combination
$
Input:
operations = ["CombinationIterator", "next", "hasNext"], parameters = [["xyz", 3], [], []]
›
Output:
[null, "xyz", false]
💡 Note:
Only one combination possible when length equals string length: the string itself.
Constraints
- 1 ≤ combinationLength ≤ characters.length ≤ 15
- characters consists of distinct lowercase English letters
- At most 104 calls will be made to next and hasNext
Visualization
Tap to expand
Understanding the Visualization
1
Input
String 'abc' with combination length 2
2
Process
Generate all combinations: ab, ac, bc in lexicographical order
3
Output
Iterator returns combinations one by one: ab → ac → bc
Key Takeaway
🎯 Key Insight: Generate combinations systematically in lexicographical order using either pre-computation or state-based iteration
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code