C++ program to find number in given range where each digit is distinct

Suppose we have two numbers l and r. We have to find an integer x, which is in between l and r (both inclusive) and all digits in x are distinct.

So, if the input is like l = 211; r = 230, then the output will be 213.


To solve this, we will follow these steps −

for initialize k := l, when k <= r, update (increase k by 1), do:
   h := convert k to string
   Define one set s
   for initialize i := 0, when i < size of h, update (increase i by 1), do:
      insert h[i] into s
   if size of s is same as size of h, then:
      return h
return "-1"


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

string solve(int l, int r) {
   for (int k = l; k <= r; k++) {
      string h = to_string(k);
      set<char> s;
      for (int i = 0; i < h.size(); i++)
      if (s.size() == h.size()) {
         return h;
   return "-1";
int main() {
   int l = 211;
   int r = 230;
   cout << solve(l, r) << endl;


211, 230