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() - Returns true if 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
Iterator for Combination: 'abc' with length 2abcGenerate all combinations of length 2abacbcnext()next()Iterator returns combinations in lexicographical order
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
32.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen