Iterator for Combination Problem
Description
LeetCode Problem 1286.
Design the CombinationIterator class:
CombinationIterator(string characters, int combinationLength)Initializes the object with a stringcharactersof sorted distinct lowercase English letters and a numbercombinationLengthas arguments.next()Returns the next combination of lengthcombinationLengthin lexicographical order.hasNext()Returnstrueif and only if there exists a next combination.
Example 1:
Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]
Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next(); // return "ab"
itr.hasNext(); // return True
itr.next(); // return "ac"
itr.hasNext(); // return True
itr.next(); // return "bc"
itr.hasNext(); // return False
Constraints:
1 <= combinationLength <= characters.length <= 15- All the characters of
charactersare unique. - At most
10^4calls will be made tonextandhasNext. - It is guaranteed that all calls of the function
nextare valid.
Solution
Approach: Precompute All Combinations
With at most 15 distinct characters there are at most C(15, 7) = 6435 combinations, so we can simply list them all in the constructor and let the iterator walk through the list.
To produce them in lexicographical order, use a depth-first search over the characters from left to right. At index i we first take characters[i] and recurse, then skip it and recurse. Because characters is sorted, every combination that contains characters[i] at this position is smaller than every combination that skips it, so the results come out already sorted. A combination is complete once it has combinationLength letters; we also stop early when there are not enough characters left to fill it.
After that, next() returns the entry at the current index and moves the index forward, and hasNext() checks whether the index is still inside the list.
Complexity: O(C(n, k) · k) time and space to build the list, where k = combinationLength; next and hasNext are O(1) (plus O(k) to copy the string out).
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
# Build every combination up front. Taking characters[i] before skipping it
# produces them in lexicographical order, because characters is sorted.
self.combos = []
picked = []
def dfs(i):
if len(picked) == combinationLength:
self.combos.append("".join(picked))
return
if len(characters) - i < combinationLength - len(picked):
return # not enough characters left
picked.append(characters[i])
dfs(i + 1)
picked.pop()
dfs(i + 1)
dfs(0)
self.idx = 0
def next(self) -> str:
self.idx += 1
return self.combos[self.idx - 1]
def hasNext(self) -> bool:
return self.idx < len(self.combos)