1286. Iterator for Combination

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.
class Solution:
    def __init__(self, characters: str, combinationLength: int): 
        self.chars = characters 
        self.N = len(self.chars) 
        self.k = combinationLength 
        self.idx = 0 
        self.end = 2 ** self.N 
         
        base = 2 ** (self.N - 1) 
        for i in range(self.k): 
            self.idx += base 
            base = base >> 1 
            
    def next(self) -> str: 
        res = [self.chars[i] for i in range(self.N) if (1 << (self.N - 1 -i)) & self.idx] 
        self.idx -= 1 
        while self.idx > 0: 
            if bin(self.idx).count('1') == self.k: 
                break 
            self.idx -= 1 
        return ''.join(res) 
             
    def hasNext(self) -> bool: 
        return self.idx > 0