#1286
Iterator for Combination
MediumStringBacktrackingDesignIteratorBacktrackingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a backtracking approach to generate combinations on-the-fly instead of storing all combinations upfront. This saves space and allows us to generate combinations in lexicographical order directly.
⚙️
Algorithm
3 steps- 1Step 1: Use a backtracking function to generate the next combination based on the current index.
- 2Step 2: Maintain a current combination string and an index to track the position in the characters string.
- 3Step 3: Implement next() and hasNext() to utilize the backtracking function.
solution.py28 lines
1class CombinationIterator:
2 def __init__(self, characters: str, combinationLength: int):
3 self.characters = characters
4 self.combinationLength = combinationLength
5 self.current = ''
6 self.index = 0
7 self.has_next = self._generate_next()
8
9 def _generate_next(self):
10 if self.index == len(self.characters):
11 return False
12 if len(self.current) == self.combinationLength:
13 return True
14 for i in range(self.index, len(self.characters)):
15 self.current += self.characters[i]
16 self.index = i + 1
17 if self._generate_next():
18 return True
19 self.current = self.current[:-1]
20 return False
21
22 def next(self) -> str:
23 result = self.current
24 self.has_next = self._generate_next()
25 return result
26
27 def hasNext(self) -> bool:
28 return self.has_nextℹ
Complexity note: The time complexity is O(n) because we generate combinations on-the-fly without storing all of them. The space complexity is O(n) for the current combination string.
- 1Understanding backtracking is crucial for generating combinations efficiently.
- 2Recognizing the need for space optimization can lead to better solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.