Problem Description
Design a CombinationIterator class that, given a string of sorted distinct lowercase letters and a combination length, precomputes all combinations of the given length in lexicographical order. Then, implement the next() method to return the next combination and the hasNext() method to check if there are more combinations.
Key Insights
- The problem involves generating all possible combinations of a fixed length from the given characters.
- Since the characters are already sorted, combinations generated using backtracking will automatically be in lexicographical order.
- Precompute all combinations using backtracking and store them in a list; then simply iterate through the list using an index pointer.
- Given the constraints, precomputing combinations has a manageable cost.
- Each call to next() and hasNext() should work in constant time after the precomputation step.
Space and Time Complexity
Time Complexity: Precomputation takes O(CombinationCount * k), where CombinationCount = C(n, k) and k is the combinationLength; each next() and hasNext() call is O(1).
Space Complexity: O(CombinationCount * k) to store all combinations.
Solution
The approach is to generate all possible combinations using backtracking and store them in an array (or equivalent data structure). When next() is called, return the current combination and increment the pointer; hasNext() simply checks if the pointer has reached the end of the precomputed list. This separation allows constant time retrieval of combinations after the initial O(CombinationCount * k) computation. The distinct characters and sorted order guarantee that the backtracking method yields combinations in lexicographical order without additional sorting.