Talentd
FleetCode

1286. Iterator for Combination

Medium72.7% acceptance1 company

Design the CombinationIterator class:

  • CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.
  • next() Returns the next combination of length combinationLength in lexicographical order.
  • hasNext() Returns true if 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 characters are unique.
  • At most 104 calls will be made to next and hasNext.
  • It is guaranteed that all calls of the function next are valid.

Asked at 1 company

Hints open one at a time

Hint 1
Generate all combinations as a preprocessing.
Hint 2
Use bit masking to generate all the combinations.
23:43
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class CombinationIterator:
2
3 def __init__(self, characters: str, combinationLength: int):
4
5
6 def next(self) -> str:
7
8
9 def hasNext(self) -> bool:
10
11
12
13# Your CombinationIterator object will be instantiated and called as such:
14# obj = CombinationIterator(characters, combinationLength)
15# param_1 = obj.next()
16# param_2 = obj.hasNext()
Starter codePython 3Spaces: 4
Examples
Input
["CombinationIterator","next","hasNext","next","hasNext","next","hasNext"]
[["abc",2],[],[],[],[],[],[]]
Your code is saved on this device.Solution