Iterator for Combination in C++

C++Server Side ProgrammingProgramming

Suppose we have to design an Iterator class, that consists of few operations −

  • Define a constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as parameter.
  • Define a function next() that returns the next combination of length combinationLength in alphabetic order.
  • Define another function hasNext() that returns True if and only if there exists a next combination.

So if the input is like −

CombinationIterator iterator = new CombinationIterator("xyz", 2);; // returns "xy"
iterator.hasNext(); // returns true; // returns "xz"
iterator.hasNext(); // returns true; // returns "yz"
iterator.hasNext(); // returns false

To solve this, we will follow these steps −

  • Create an array comb of strings, and index idx
  • Define a method makeCombs(), this will take string s, integer variable l, a temp string, that is initially empty, and start, that is initially 0. This is defined as follows −
  • if size of temp = l, then insert temp into comb and return
  • for i in range start to size of s
    • makeCombs(s, l, temp + s[i], i + 1)
  • printVector() method will take the array of string as input, this will display the elements of that array
  • Define the constructor as follows: this will take string c and cl,
  • call makeCombs(c, cl), set idx := 0
  • The next() method will increase idx and return comb[idx - 1]
  • the hasNext() method will return true if idx is not same as size of comb, otherwise false.


Let us see the following implementation to get better understanding −

class CombinationIterator {
   vector <string> combs;
   int idx;
   void makeCombs(string s, int l, string temp ="", int start = 0){
      if(temp.size() == l){
      for(int i = start; i < s.size(); i++){
         makeCombs(s, l, temp + s[i], i + 1);
   void printVector(vector <string> v){
      for(int i = 0; i < v.size(); i++){
         cout << v[i] << "\n";
      cout << endl;
   CombinationIterator(string c, int cl) {
      makeCombs(c, cl);
      idx = 0;
   string next() {
      return combs[idx - 1];
   bool hasNext() {
      return !(idx == combs.size());
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();




Published on 17-Mar-2020 12:06:14