Skip to content

Latest commit

 

History

History
77 lines (65 loc) · 2.85 KB

README.md

File metadata and controls

77 lines (65 loc) · 2.85 KB

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's guaranteed that all calls of the function next are valid.

Companies:
Amazon, Google

Related Topics:
String, Backtracking, Design, Iterator

Solution 1.

// OJ: https://leetcode.com/problems/iterator-for-combination/
// Author: github.com/lzl124631x
// Time:
//      CombinationIterator: O(S)
//      next: O(L)
//      hasNext: O(1)
// Space: O(S)
class CombinationIterator {
    string s;
    vector<int> index;
public:
    CombinationIterator(string s, int len) : s(s), index(len) {
        iota(begin(index), end(index), 0);
    }
    string next() {
        string ans;
        for (int n : index) ans += s[n];
        int i = index.size() - 1; // find the first from right index that should be incremented.
        while (i > 0 && index[i] == s.size() - index.size() + i) --i;
        ++index[i++];
        for (; i < index.size(); ++i) index[i] = index[i - 1] + 1;
        return ans;
    }
    bool hasNext() {
        return index[0] <= s.size() - index.size();
    }
};