Next greater Number than N with the same quantity of digits A and B in C++

C++Server Side ProgrammingProgramming

Given N, A, and B. Find the number which is greater than N with the same number of and digits. Let's see an example.

N = 1234
A = 2
B = 3

We need to check for every possibility of the given number of digits. There are two digits to form the number. And each digit count in the number should be the same.


  • Initialise A, B, and N.

  • Write a recursive function.

    • Check whether the current number is greater than and has equal number of and digits.

    • Return the number if the above condition satisfies.

    • Add the digit A to the result.
    • Add the digit B to the result.
    • Recursively call the function with the minimum number from the above two.


Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
long getNextGreaterElement(long result, int A, int A_Count, int B, int B_Count, int N) {
   if (result > 1e11) {
      return 1e11;
   if (A_Count == B_Count && result >= N) {
      return result;
   return min(getNextGreaterElement(result * 10 + A, A, A_Count + 1, B, B_Count, N),       getNextGreaterElement(result * 10 + B, A, A_Count, B, B_Count + 1, N));
int main() {
   int N = 1234;
   int A = 2;
   int B = 3;
   cout << getNextGreaterElement(0, A, 0, B, 0, N) << endl;
   return 0;


If you run the above code, then you will get the following result.

Updated on 25-Oct-2021 03:46:00