The Wayback Machine - https://web.archive.org/web/20240707120657/https://www.geeksforgeeks.org/find-next-greater-number-set-digits/
Open In App

Find next greater number with same set of digits

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n, find the smallest number that has same set of digits as n and is greater than n. If n is the greatest possible number with its set of digits, then print “not possible”.

Examples: 
For simplicity of implementation, we have considered input number as a string. 

Input:  n = "218765"
Output: "251678"

Input:  n = "1234"
Output: "1243"

Input: n = "4321"
Output: "Not Possible"

Input: n = "534976"
Output: "536479"
Recommended Practice

Following are few observations about the next greater number. 

  1. If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321. 
  2. If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234. 
  3. For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)

You can now try developing an algorithm yourself. 

Following is the algorithm for finding the next greater number. 

  1. Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
  2. Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
  3. Swap the above found two digits, we get 536974 in above example.
  4. Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.

Following are the implementation of above approach. 

C++




// C++ program to find the smallest number which greater than a given number
// and has same set of digits as given number
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
  
// Utility function to swap two digits
void swap(char *a, char *b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}
  
// Given a number as a char array number[], this function finds the
// next greater number.  It modifies the same array to store the result
void findNext(char number[], int n)
{
    int i, j;
  
    // I) Start from the right most digit and find the first digit that is
    // smaller than the digit next to it.
    for (i = n-1; i > 0; i--)
        if (number[i] > number[i-1])
           break;
  
    // If no such digit is found, then all digits are in descending order
    // means there cannot be a greater number with same set of digits
    if (i==0)
    {
        cout << "Next number is not possible";
        return;
    }
  
    // II) Find the smallest digit on right side of (i-1)'th digit that is
    // greater than number[i-1]
    int x = number[i-1], smallest = i;
    for (j = i+1; j < n; j++)
        if (number[j] > x && number[j] < number[smallest])
            smallest = j;
  
    // III) Swap the above found smallest digit with number[i-1]
    swap(&number;[smallest], &number;[i-1]);
  
    // IV) Sort the digits after (i-1) in ascending order
    sort(number + i, number + n);
  
    cout << "Next number with same set of digits is " << number;
  
    return;
}
  
// Driver program to test above function
int main()
{
    char digits[] = "534976";
    int n = strlen(digits);
    findNext(digits, n);
    return 0;
}


Java




// Java program to find next greater 
// number with same set of digits.
import java.util.Arrays;
  
public class nextGreater 
{
    // Utility function to swap two digit
    static void swap(char ar[], int i, int j) 
    {
        char temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
  
    // Given a number as a char array number[], 
    // this function finds the next greater number. 
    // It modifies the same array to store the result
    static void findNext(char ar[], int n) 
    {
        int i;
          
        // I) Start from the right most digit 
        // and find the first digit that is smaller 
        // than the digit next to it.
        for (i = n - 1; i > 0; i--) 
        {
            if (ar[i] > ar[i - 1]) {
                break;
            }
        }
          
        // If no such digit is found, then all 
        // digits are in descending order means 
        // there cannot be a greater number with 
        // same set of digits
        if (i == 0) 
        {
            System.out.println("Not possible");
        } 
        else 
        {
            int x = ar[i - 1], min = i;
              
            // II) Find the smallest digit on right 
            // side of (i-1)'th digit that is greater 
            // than number[i-1]
            for (int j = i + 1; j < n; j++) 
            {
                if (ar[j] > x && ar[j] < ar[min]) 
                {
                    min = j;
                }
            }
  
            // III) Swap the above found smallest 
            // digit with number[i-1]
            swap(ar, i - 1, min);
  
            // IV) Sort the digits after (i-1) 
            // in ascending order
            Arrays.sort(ar, i, n);
            System.out.print("Next number with same" +
                                    " set of digits is ");
            for (i = 0; i < n; i++)
                System.out.print(ar[i]);
        }
    }
  
    public static void main(String[] args) 
    {
        char digits[] = { '5','3','4','9','7','6' };
        int n = digits.length;
        findNext(digits, n);
    }
}


Python3




# Python program to find the smallest number which 
# is greater than a given no. has same set of 
# digits as given number
  
# Given number as int array, this function finds the 
# greatest number and returns the number as integer
def findNext(number,n):
       
     # Start from the right most digit and find the first
     # digit that is smaller than the digit next to it
     for i in range(n-1,0,-1):
         if number[i] > number[i-1]:
             break
               
     # If no such digit found,then all numbers are in 
     # descending order, no greater number is possible
     if i == 1 and number[i] <= number[i-1]:
         print ("Next number not possible")
         return
           
     # Find the smallest digit on the right side of 
     # (i-1)'th digit that is greater than number[i-1]
     x = number[i-1]
     smallest = i
     for j in range(i+1,n):
         if number[j] > x and number[j] < number[smallest]:
             smallest = j
           
     # Swapping the above found smallest digit with (i-1)'th
     number[smallest],number[i-1] = number[i-1], number[smallest]
       
     # X is the final number, in integer datatype 
     x = 0
     # Converting list upto i-1 into number
     for j in range(i):
         x = x * 10 + number[j]
       
     # Sort the digits after i-1 in ascending order
     number = sorted(number[i:])
     # converting the remaining sorted digits into number
     for j in range(n-i):
         x = x * 10 + number[j]
       
     print ("Next number with set of digits is",x)
  
  
# Driver Program to test above function
digits = "534976"         
  
# converting into integer array,
# number becomes [5,3,4,9,7,6]
number = list(map(int ,digits))
findNext(number, len(digits))
  
# This code is contributed by Harshit Agrawal


C#




// C# program to find next greater 
// number with same set of digits.
using System;
                      
public class nextGreater 
{
    // Utility function to swap two digit
    static void swap(char []ar, int i, int j) 
    {
        char temp = ar[i];
        ar[i] = ar[j];
        ar[j] = temp;
    }
  
    // Given a number as a char array number[], 
    // this function finds the next greater number. 
    // It modifies the same array to store the result
    static void findNext(char []ar, int n) 
    {
        int i;
          
        // I) Start from the right most digit 
        // and find the first digit that is smaller 
        // than the digit next to it.
        for (i = n - 1; i > 0; i--) 
        {
            if (ar[i] > ar[i - 1]) 
            {
                break;
            }
        }
          
        // If no such digit is found, then all 
        // digits are in descending order means 
        // there cannot be a greater number with 
        // same set of digits
        if (i == 0) 
        {
            Console.WriteLine("Not possible");
        } 
        else
        {
            int x = ar[i - 1], min = i;
              
            // II) Find the smallest digit on right 
            // side of (i-1)'th digit that is greater 
            // than number[i-1]
            for (int j = i + 1; j < n; j++) 
            {
                if (ar[j] > x && ar[j] < ar[min]) 
                {
                    min = j;
                }
            }
  
            // III) Swap the above found smallest 
            // digit with number[i-1]
            swap(ar, i - 1, min);
  
            // IV) Sort the digits after (i-1) 
            // in ascending order
            Array.Sort(ar, i, n-i);
            Console.Write("Next number with same" +
                                    " set of digits is ");
            for (i = 0; i < n; i++)
                Console.Write(ar[i]);
        }
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        char []digits = { '5','3','4','9','7','6' };
        int n = digits.Length;
        findNext(digits, n);
    }
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
  
// JavaScript program to find the 
// smallest number which is greater
// than a given no. has same set of 
// digits as given number
  
// Given number as int array, this 
// function finds the greatest number
// and returns the number as integer
function findNext(number, n)
{
      
    // Start from the right most digit 
    // and find the first digit that is
    // smaller than the digit next to it
    for(var i = n - 1; i >= 0; i--)
    {
        if (number[i] > number[i - 1])
            break;
    }
      
    // If no such digit found,then all 
    // numbers are in descending order,
    // no greater number is possible
    if (i == 1 && number[i] <= number[i - 1])
    {
        document.write("Next number not possible");
        return;
    }   
      
    // Find the smallest digit on the
    // right side of (i-1)'th digit
    // that is greater than number[i-1]
    let x = number[i - 1];
    let smallest = i;
      
    for(let j = i + 1; j < n; j++)
    {
        if (number[j] > x && 
            number[j] < number[smallest])
        smallest = j;
    }
      
    // Swapping the above found smallest 
    // digit with (i-1)'th
    let temp = number[smallest];
    number[smallest] = number[i - 1];
    number[i - 1] = temp;
      
    // X is the final number, in integer datatype 
    x = 0
      
    // Converting list upto i-1 into number
    for(let j = 0; j < i; j++)
        x = x * 10 + number[j];
      
    // Sort the digits after i-1 in ascending order
    number = number.slice(i, number.length + 1);
    number.sort()
      
    // Converting the remaining sorted
    // digits into number
    for(let j = 0; j < n - i; j++)
        x = x * 10 + number[j];
      
    document.write("Next number with " + 
                   "set of digits is " + x);
}
  
// Driver code
let digits = "534976"       
  
// Converting into integer array,
// number becomes [5,3,4,9,7,6]
let number = []
for(let i = 0; i < digits.length; i++)
    number[i] = Number(digits[i]);
  
findNext(number, digits.length);
  
// This code is contributed by rohan07
  
</script>


Output

Next number with same set of digits is 536479

Time Complexity: O(N*logN) 
Auxiliary Space: O(1)

The above implementation can be optimized in following ways. 

  1. We can use binary search in step II instead of linear search. 
  2. In step IV, instead of doing simple sort, we can apply some clever technique to do it in linear time. Hint: We know that all digits are linearly sorted in reverse order except one digit which was swapped.

With above optimizations, we can say that the time complexity of this method is O(n). 

Optimised Approach:

  1. Here instead of sorting the digits after (i-1) index, we are reversing the digits as mentioned in the above optimisation point.
  2. As they will be in decreasing order so to find the smallest element possible from the right part we just reverse them thus reducing time complexity.

Below is the implementation of the above approach:

C++14




#include <bits/stdc++.h>
using namespace std;
  
vector<int> nextPermutation(int n, vector<int> arr)
{
    // If number of digits is 1 then just return the vector
    if (n == 1)
        return arr;
  
    // Start from the right most digit and find the first
    // digit that is
    // smaller than the digit next to it.
    int i = 0;
    for (i = n - 1; i > 0; i--) {
        if (arr[i] > arr[i - 1])
            break;
    }
  
    // If there is a possibility of a next greater element
    if (i != 0) {
        // Find the smallest digit on right side of (i-1)'th
        // digit that is
        // greater than number[i-1]
        for (int j = n - 1; j >= i; j--) {
            if (arr[i - 1] < arr[j]) {
                // Swap the found smallest digit i.e. arr[j]
                // with arr[i-1]
                swap(arr[i - 1], arr[j]);
                break;
            }
        }
    }
  
    // Reverse the digits after (i-1) because the digits
    // after (i-1) are in decreasing order and thus we will
    // get the smallest element possible from these digits
    reverse(arr.begin() + i, arr.end());
  
    // If i is 0 that means elements are in decreasing order
    // Therefore, no greater element possible then we just
    // return the lowest possible
    // order/element formed from these digits by just
    // reversing the vector
  
    return arr;
}
  
int main()
{
    int n = 6;
    vector<int> v{ 5,3,4,9,7,6 };
    vector<int> res;
    res = nextPermutation(n, v);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " ";
    }
}


Java




// Java implementation of the approach
import java.util.*;
  
class GFG
{
  static int[] nextPermutation(int n, int[] arr)
  {
  
    // If number of digits is 1 then just return the vector
    if (n == 1)
      return arr;
  
    // Start from the right most digit and find the first
    // digit that is
    // smaller than the digit next to it.
    int i = 0;
    for (i = n - 1; i > 0; i--) {
      if (arr[i] > arr[i - 1])
        break;
    }
  
    // If there is a possibility of a next greater element
    if (i != 0)
    {
  
      // Find the smallest digit on right side of (i-1)'th
      // digit that is
      // greater than number[i-1]
      for (int j = n - 1; j >= i; j--) 
      {
        if (arr[i - 1] < arr[j])
        {
  
          // Swap the found smallest digit i.e. arr[j]
          // with arr[i-1]
          int temp = arr[j];
          arr[j] = arr[i - 1];
          arr[i - 1] = temp;
          break;
        }
      }
    }
  
    // Reverse the digits after (i-1) because the digits
    // after (i-1) are in decreasing order and thus we will
    // get the smallest element possible from these digits
    int[] res = new int[arr.length];
    int ind = arr.length - 1;
  
    // copying the first i elements of arr
    // into res
    for (int j = 0; j < i; j++)
      res[j] = arr[j];
  
    // copying the rest of the elements
    // in reverse order
    for (int j = i; j< res.length; j++)
      res[j] = arr[ind--];
  
    // If i is 0 that means elements are in decreasing order
    // Therefore, no greater element possible then we just
    // return the lowest possible
    // order/element formed from these digits by just
    // reversing the vector
    return res;
  }
  
  // Driver Code
  public static void main(String[] args)
  {
    int n = 6;
    int[] v = { 5,3,4,9,7,6 };
    int[] res;
  
    // Function Call
    res = nextPermutation(n, v);
    for (int i = 0; i < res.length; i++) {
      System.out.print(res[i] + " ");
    }
  }
}
  
// This code is contributed by phasing17


Python3




# A python program to find the next greatest number
def nextPermutation(arr):
    
      # find the length of the array
    n = len(arr)
      
    # start from the right most digit and find the first
    # digit that is smaller than the digit next to it.
    k = n - 2
    while k >= 0:
        if arr[k] < arr[k + 1]:
            break
        k -= 1
          
    # reverse the list if the digit that is smaller than the
    # digit next to it is not found.
    if k < 0:
        arr = arr[::-1]
    else:
        
          # find the first greatest element than arr[k] from the 
        # end of the list
        for l in range(n - 1, k, -1):
            if arr[l] > arr[k]:
                break
  
        # swap the elements at arr[k] and arr[l      
        arr[l], arr[k] = arr[k], arr[l]
          
        # reverse the list from k + 1 to the end to find the 
        # most nearest greater number to the given input number
        arr[k + 1:] = reversed(arr[k + 1:])
  
    return arr
  
# Driver code
arr = [5, 3, 4, 9, 7, 6]
print(*nextPermutation(arr))
  
# This code is contributed by Manish Thapa


C#




// C# implementation of the approach
using System;
class GFG {
  static int[] nextPermutation(int n, int[] arr)
  {
  
    // If number of digits is 1 then just return the
    // vector
    if (n == 1)
      return arr;
  
    // Start from the right most digit and find the
    // first digit that is smaller than the digit next
    // to it.
    int i = 0;
    for (i = n - 1; i > 0; i--) {
      if (arr[i] > arr[i - 1])
        break;
    }
  
    // If there is a possibility of a next greater
    // element
    if (i != 0) {
  
      // Find the smallest digit on right side of
      // (i-1)'th digit that is greater than
      // number[i-1]
      for (int j = n - 1; j >= i; j--) {
        if (arr[i - 1] < arr[j]) {
  
          // Swap the found smallest digit i.e.
          // arr[j] with arr[i-1]
          int temp = arr[j];
          arr[j] = arr[i - 1];
          arr[i - 1] = temp;
          break;
        }
      }
    }
  
    // Reverse the digits after (i-1) because the digits
    // after (i-1) are in decreasing order and thus we
    // will get the smallest element possible from these
    // digits
    int[] res = new int[arr.Length];
    int ind = arr.Length - 1;
  
    // copying the first i elements of arr
    // into res
    for (int j = 0; j < i; j++)
      res[j] = arr[j];
  
    // copying the rest of the elements
    // in reverse order
    for (int j = i; j < res.Length; j++)
      res[j] = arr[ind--];
  
    // If i is 0 that means elements are in decreasing
    // order Therefore, no greater element possible then
    // we just return the lowest possible order/element
    // formed from these digits by just reversing the
    // vector
    return res;
  }
  
  // Driver Code
  public static int Main()
  {
    int n = 6;
    int[] v = new int[] { 5, 3, 4, 9, 7, 6 };
    int[] res;
  
    // Function Call
    res = nextPermutation(n, v);
    for (int i = 0; i < res.Length; i++) {
      Console.Write(res[i] + " ");
    }
    return 0;
  }
}
  
// This code is contributed by Taranpreet


Javascript




<script>
  
function nextPermutation(n, arr)
{
    // If number of digits is 1 then just return the vector
    if (n == 1)
        return arr;
   
    // Start from the right most digit and find the first
    // digit that is
    // smaller than the digit next to it.
    let i = 0;
    for (i = n - 1; i > 0; i--) {
        if (arr[i] > arr[i - 1])
            break;
    }
   
    // If there is a possibility of a next greater element
    if (i != 0)
    {
      
        // Find the smallest digit on right side of (i-1)'th
        // digit that is
        // greater than number[i-1]
        for (let j = n - 1; j >= i; j--)
        {
            if (arr[i - 1] < arr[j])
            {
                // Swap the found smallest digit i.e. arr[j]
                // with arr[i-1]
                  
                let temp = arr[i - 1];
                arr[i - 1] = arr[j];
                arr[j] = temp;
                break;
            }
        }
    }
   
    // Reverse the digits after (i-1) because the digits
    // after (i-1) are in decreasing order and thus we will
    // get the smallest element possible from these digits
    arr = arr.slice(0,i).concat(arr.slice(i,arr.length).reverse());
   
    // If i is 0 that means elements are in decreasing order
    // Therefore, no greater element possible then we just
    // return the lowest possible
    // order/element formed from these digits by just
    // reversing the vector
    return arr;
}
  
let v = [5,3,4,9,7,6];
let n = 6;
let res = nextPermutation(n, v);
for (let i = 0; i < res.length; i++) {
    document.write(res[i] + " ")
}
  
// This code is contributed by avanitrachhadiya2155
</script>


Output

5 3 6 4 7 9 

Time Complexity: O(N)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Next greater Number than N with the same quantity of digits A and B
Given a number [Tex]N [/Tex]and two digits [Tex]A [/Tex]and [Tex]B [/Tex]. The task is to find the least number not less than N which contains the equal number of digits A and B.Note: N &lt;= 107Examples: Input : N = 4500, A = 4, B = 7 Output : 4747 The number greater than 4500 which has the same quantity of number '4' and number '7' is 4747.Input
7 min read
Closest (or Next) smaller and greater numbers with same number of set bits
Given a positive integer n, print the next smallest and the previous largest number that has the same number of 1 bit in their binary representation. Examples: Input : n = 5 Output : Closest Greater = 6 Closest Smaller = 3 Note that 5, 6 and 3 have same number of set bits. Input : n = 11 Output : Closest Greater = 13 Closest Smaller = 7 The Brute F
15+ min read
Find next greater number formed with exactly two unique digits for each Array element
Given an array arr[] having N integers, the task is to find the next greater number X i.e, X &gt;= arr[i] for each i in the range [0, N) such that the count of unique digits in X is exactly 2. Example: Input: arr[] = {123, 234}Output: 131 242Explanation: For the given array, 131 is the smallest number greater that 123 having exactly 2 unique digits
11 min read
Binary representation of next greater number with same number of 1's and 0's
Given a binary input that represents binary representation of positive number n, find binary representation of smallest number greater than n with same number of 1's and 0's as in binary representation of n. If no such number can be formed, print "no greater number".The binary input may be and may not fit even in unsigned long long int. Examples: I
12 min read
Find next Smaller of next Greater in an array
Given array of integer, find the next smaller of next greater element of every element in array. Note : Elements for which no greater element exists or no smaller of greater element exist, print -1. Examples: Input : arr[] = {5, 1, 9, 2, 5, 1, 7} Output: 2 2 -1 1 -1 -1 -1 Explanation : Next Greater -&gt; Right Smaller 5 -&gt; 9 9 -&gt; 2 1 -&gt; 9
14 min read
Minimum digits to be removed to make either all digits or alternating digits same
Given a numeric string str, the task is to find the minimum number of digits to be removed from the string such that it satisfies either of the below conditions: All the elements of the string are the same.All the elements at even position are same and all the elements at the odd position are same, which means the string is alternating with the equ
7 min read
Next higher palindromic number using the same set of digits
Given a palindromic number num having n number of digits. The problem is to find the smallest palindromic number greater than num using the same set of digits as in num. If no such number can be formed then print "Not Possible". The number could be very large and may or may not even fit into long long int. Examples: Input : 4697557964Output : 47569
15+ min read
Lexicographically next greater string using same character set
Given a number K and a string S, We have to Find the lexicographically smallest string str of length K such that it's set of letters is a subset of the set of letters of S and S is lexicographically smaller than str. Examples: Input :k = 3 s = zbf Output: zbz Explanation: zbz is greater than zbf and it is smaller than any other lexicographically gr
8 min read
Next greater number on the basis of precedence of digits
Given a number num containing n digits. The problem is to find the next greater number using the same set of digits in num on the basis of the given precedence of digits. For example the precedence of digits is given as 1, 6, 4, 5, 2, 9, 8, 0, 7, 3 which simply means 1 &lt; 6 &lt; 4 &lt; 5 &lt; 2 &lt; 9 &lt; 8 &lt; 0 &lt; 7 &lt; 3. If next greater
10 min read
Next higher number with same number of set bits
Given a number x, find next number with same number of 1 bits in it's binary representation.For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).Algorithm:When we observe the binary sequence from 0 to 2
8 min read
three90RightbarBannerImg