LeetCode 1286. Iterator for Combination Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1286. Iterator for Combination

Description

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.

Solutions

Solution 1

PythonJavaC++Go
class CombinationIterator: def __init__(self, characters: str, combinationLength: int): def dfs(i): if len(t) == combinationLength: cs.append(''.join(t)) return if i == n: return t.append(characters[i]) dfs(i + 1) t.pop() dfs(i + 1) cs = [] n = len(characters) t = [] dfs(0) self.cs = cs self.idx = 0 def next(self) -> str: ans = self.cs[self.idx] self.idx += 1 return ans def hasNext(self) -> bool: return self.idx < len(self.cs) # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext()(code-box)

Solution 2

PythonJavaC++Go
class CombinationIterator: def __init__(self, characters: str, combinationLength: int): self.curr = (1 << len(characters)) - 1 self.size = combinationLength self.cs = characters[::-1] def next(self) -> str: while self.curr >= 0 and self.curr.bit_count() != self.size: self.curr -= 1 ans = [] for i in range(len(self.cs)): if (self.curr >> i) & 1: ans.append(self.cs[i]) self.curr -= 1 return ''.join(ans[::-1]) def hasNext(self) -> bool: while self.curr >= 0 and self.curr.bit_count() != self.size: self.curr -= 1 return self.curr >= 0 # Your CombinationIterator object will be instantiated and called as such: # obj = CombinationIterator(characters, combinationLength) # param_1 = obj.next() # param_2 = obj.hasNext()(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !