Print a number strictly less than a given number such that all its digits are distinct in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number n. Our task is to print the largest number less than n such that all its digits are distinct.

Let’s take an example to understand the problem

Input: n = 2332
Output: 2319

To solve this problem, we reverse the count of the numbers i.e. from n to 0. And check for number with distinct digits, if the current count values satisfy the condition print it and end the loop. Otherwise continue to loop. The max number of times the loop will run is always less than n.


Program to implement our solutions,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findDistinctDigitNumber(int n) {
   for (int i = n - 1; i>=0 ; i--) {
      int count[10] = { 0 };
      int x = i;
      int count1 = 0, count2 = 0;
      while (x) {
         count[x % 10]++;
         x /= 10;
      for (int j = 0; j < 10; j++) {
         if (count[j] == 1)
      if (count1 == count2)
      return i;
int main() {
   int n = 44324;
   cout<<"Number less than "<<n<<" with all digits distinct are : "<<findDistinctDigitNumber(n);
   return 0;


Number less than 44324 with all digits distinct are : 43987
Published on 27-Jan-2020 10:52:56