Skip to main content
Back to problems
#1286
Medium Algorithms

Iterator for combination

String Backtracking Design Iterator
72.7% acceptance
Feb 25, 2026
1390
108
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
pub struct CombinationIterator {
  combinations: Vec<String>,
  index: usize,
}

impl CombinationIterator {
  pub fn new(characters: String, combination_length: i32) -> Self {
    let chars: Vec<char> = characters.chars().collect();
    let n = chars.len();
    let k = combination_length as usize;
    let mut combinations = vec![];
    // Generate all combinations using bitmask
    for mask in 0u32..(1 << n) {
      if mask.count_ones() as usize == k {
        let s: String = (0..n)
          .rev()
          .filter(|&i| mask & (1 << i) != 0)
          .map(|i| chars[n - 1 - i])
          .collect();
        combinations.push(s);
      }
    }
    combinations.sort();
    CombinationIterator { combinations, index: 0 }
  }

  pub fn next(&mut self) -> String {
    let s = self.combinations[self.index].clone();
    self.index += 1;
    s
  }

  pub fn has_next(&self) -> bool {
    self.index < self.combinations.len()
  }
}