Python bit manipulation (Easy to understand)
The hints clearly says to use bitmasking. From problem statement we observe that maximum length of string would be 15, which is nothing but "111111111111111" in
The hints clearly says to use bitmasking. From problem statement we observe that maximum length of string would be 15, which is nothing but ```"111111111111111"``` in binary, whose decimal would be ```32767```. \n\n**GENERATION OF COMBINATIONS**:\nThe idea here is to run a loop from 0 to a decimal number which has ```len(characters)``` of binary digits and all bits are set. Check number of set bits in each number in its binary form. Keep those numbers in an array. \n\nThe problem statement asks us to print the combinations in **lexicographical order.** Don\'t give a sweat, as the power of binary comes to rescue. The generated combination will already be in reverse order.\n\nEg: "abc", 2\n* We start with ```"111"``` which is 7. Run a loop over 0 to 7 both inclusive. The possible values with 2 set bits are ```["011", "101", "110"]```\n\n**PRINTING next:**\nJust take the appropriate combination. Run a loop. If the bit is set, include the char in the given position in the initial character.\n\n**hasNext is a cake walk :P**\n\n**SOLUTION**\n\n```\nclass CombinationIterator:\n\n    def __init__(self, characters: str, combinationLength: int):\n        self.characters = characters\n        self.n = len(characters)\n        self.combinations = gen_combinations(self.n, combinationLength)\n        self.ind = len(self.combinations) - 1\n\n    def next(self) -> str:\n        s = ""\n        for i in range(self.n):\n            if self.combinations[self.ind][i] != "0":\n                s += self.characters[i]\n        self.ind -= 1\n        return s\n\n    def hasNext(self) -> bool:\n        return self.ind > -1 \n    \ndef gen_combinations(l, n):\n    end = int("1" * l, 2)\n    ans = []\n    for i in range(end + 1):\n        b = bin(i)[2:]\n        if b.count(\'1\') == n:\n            ans.append(b.zfill(l))\n    return ans\n```\n
[]