#1286

Iterator for Combination

pupil · 530 · lc medium +28 · 72.7% accepted · 1,390 likes · top 82%

Description

Implement a CombinationIterator class that lazily produces character combinations in lexicographic order:

- CombinationIterator(characters, combinationLength): Initializes the iterator with a sorted string characters of distinct lowercase letters and a target length combinationLength.
- next(): Returns the lexicographically next combination of length combinationLength.
- hasNext(): Returns true if more combinations remain.

Example 1:

Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]

Example 2:

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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16