Find next greater number with same set of digits (original) (raw)

Last Updated : 23 Jul, 2025

Given a number **N as string, 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:

**Input: N = "218765"
**Output: "251678"
**Explanation: The next number greater than 218765 with same set of digits is 251678.

**Input: n = "1234"
**Output: "1243"
**Explanation: The next number greater than 1234 with same set of digits is 1243.

**Input: n = "4321"
**Output: "Not Possible"
**Explanation: 4321 is the greatest number possible with same set of digits.\

Try It Yourselfredirect icon

Table of Content

[Naive Approach] Finding all possible permutations - O(N * N!) Time and O(N) Space:

Find all the possible permutations of the given string and then for each permutation, check if it greater than N or not. Among all the strings which are greater than N, the smallest one is the answer.

[Expected Approach] Finding Next Permutation - O(N) Time and O(1) Space:

On observing carefully, we can say that the next number which is greater than N and has the same digits as N is the next permutation of string N. We can simply find the next permutation by following the below steps:

Below is the implementation of the above approach:

C++14 `

// C++ Program to find the next greater number same set of // digits

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

string nextPermutation(string N) { // If number of digits is 1 then just return the vector if (N.length() == 1) { return "Not Possible"; }

// 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.length() - 1; i > 0; i--) {
    if (N[i] > N[i - 1])
        break;
}

// If i is 0 that means elements are in decreasing order
// Therefore, no greater element possible
if (i == 0) {
    return "Not Possible";
}

// Find the smallest digit on right side of (i-1)'th
// digit that is greater than N[i-1]
for (int j = N.length() - 1; j >= i; j--) {
    if (N[i - 1] < N[j]) {
        // Swap the found smallest digit i.e. N[j]
        // with N[i-1]
        swap(N[i - 1], N[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(N.begin() + i, N.end());

return N;

}

int main() { // Sample Input string N = "218765";

// Function Call
cout << nextPermutation(N);

}

Java

// Java Program to find the next greater number same set of // digits

import java.util.*;

public class GFG {

// Function to find the next permutation of a given
// string
static String nextPermutation(String N)
{
    // If number of digits is 1 then just return "Not
    // Possible"
    if (N.length() == 1) {
        return "Not Possible";
    }

    // Start from the right most digit and find the
    // first digit that is smaller than the digit next
    // to it.
    int i;
    for (i = N.length() - 1; i > 0; i--) {
        if (N.charAt(i) > N.charAt(i - 1)) {
            break;
        }
    }

    // If i is 0 that means elements are in decreasing
    // order. Therefore, no greater element possible.
    if (i == 0) {
        return "Not Possible";
    }

    // Find the smallest digit on right side of (i-1)'th
    // digit that is greater than N.charAt(i-1)
    for (int j = N.length() - 1; j >= i; j--) {
        if (N.charAt(i - 1) < N.charAt(j)) {
            // Swap the found smallest digit i.e.
            // N.charAt(j) with N.charAt(i-1)
            char[] charArray = N.toCharArray();
            char temp = charArray[i - 1];
            charArray[i - 1] = charArray[j];
            charArray[j] = temp;
            N = new String(charArray);
            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
    char[] charArray = N.toCharArray();
    reverse(charArray, i, N.length() - 1);
    return new String(charArray);
}

// Utility function to reverse a portion of a character
// array
static void reverse(char[] arr, int start, int end)
{
    while (start < end) {
        char temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

// Main method to test the function
public static void main(String[] args)
{
    // Sample Input
    String N = "218765";

    // Function Call
    System.out.println(nextPermutation(N));
}

}

Python

Python Program to find the next greater number same set of

digits

def nextPermutation(N): # If number of digits is 1 then just return "Not Possible" if len(N) == 1: return "Not Possible"

# Start from the right most digit and find the first digit
# that is smaller than the digit next to it.
i = len(N) - 1
while i > 0:
    if N[i] > N[i - 1]:
        break
    i -= 1

# If i is 0 that means elements are in decreasing order.
# Therefore, no greater element possible.
if i == 0:
    return "Not Possible"

# Find the smallest digit on right side of (i-1)'th digit
# that is greater than N[i-1]
for j in range(len(N) - 1, i - 1, -1):
    if N[i - 1] < N[j]:
        # Swap the found smallest digit i.e. N[j] with N[i-1]
        N = list(N)
        N[i - 1], N[j] = N[j], N[i - 1]
        N = ''.join(N)
        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
N = list(N)
N[i:] = reversed(N[i:])
N = ''.join(N)

return N

Sample Input

N = "218765"

Function Call

print(nextPermutation(N))

C#

// C# Program to find the next greater number same set of // digits

using System;

class GFG { // Function to find the next permutation of a given string static string NextPermutation(string N) { // If number of digits is 1 then just return "Not Possible" if (N.Length == 1) { return "Not Possible"; }

    // Start from the right most digit and find the first digit that is smaller than the digit next to it.
    int i;
    for (i = N.Length - 1; i > 0; i--)
    {
        if (N[i] > N[i - 1])
        {
            break;
        }
    }

    // If i is 0 that means elements are in decreasing order. Therefore, no greater element possible.
    if (i == 0)
    {
        return "Not Possible";
    }

    // Find the smallest digit on right side of (i-1)'th digit that is greater than N[i-1]
    for (int j = N.Length - 1; j >= i; j--)
    {
        if (N[i - 1] < N[j])
        {
            // Swap the found smallest digit i.e. N[j] with N[i-1]
            char[] charArray = N.ToCharArray();
            char temp = charArray[i - 1];
            charArray[i - 1] = charArray[j];
            charArray[j] = temp;
            N = new string(charArray);
            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
    char[] chars = N.ToCharArray();
    Array.Reverse(chars, i, N.Length - i);
    N = new string(chars);

    return N;
}

// Main method to test the function
static void Main()
{
    // Sample Input
    string N = "218765";

    // Function Call
    Console.WriteLine(NextPermutation(N));
}

}

JavaScript

function nextPermutation(N) { // If number of digits is 1 then just return "Not Possible" if (N.length === 1) { return "Not Possible"; }

// Start from the right most digit and find the first
// digit that is smaller than the digit next to it.
let i = N.length - 1;
while (i > 0) {
    if (N[i] > N[i - 1]) {
        break;
    }
    i--;
}

// If i is 0 that means elements are in decreasing order
// Therefore, no greater element possible
if (i === 0) {
    return "Not Possible";
}

// Find the smallest digit on right side of (i-1)'th
// digit that is greater than N[i-1]
for (let j = N.length - 1; j >= i; j--) {
    if (N[i - 1] < N[j]) {
        // Swap the found smallest digit i.e. N[j]
        // with N[i-1]
        let chars = N.split('');
        let temp = chars[i - 1];
        chars[i - 1] = chars[j];
        chars[j] = temp;
        N = chars.join('');
        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
let chars = N.split('');
reverse(chars, i);
N = chars.join('');

return N;

}

function reverse(arr, start) { let end = arr.length - 1; while (start < end) { let temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } }

// Main function to test the nextPermutation function function main() { // Sample Input let N = "218765";

// Function Call
console.log(nextPermutation(N));

}

// Execute the main function main();

`

**Time Complexity: O(N), where **N is the number of digits in input, that is the length of string.
**Auxiliary Space: O(1)