Open In App

Largest number smaller than or equal to n and digits in non-decreasing order

Last Updated : 24 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number n, find the Largest number smaller than or equal to n and digits in non-decreasing order. 

Examples: 

Input  : n = 200
Output : 199
If the given number is 200, the largest 
number which is smaller or equal to it 
having digits in non decreasing order is
199.

Input  : n = 139
Output : 139
Recommended Practice

Method 1 (Brute Force) 
Start from n, for every number check if its digits are in non decreasing order. If yes, then return. Else check for the next number until we find the result.  

C++




/* C++ program for brute force approach to find
   largest number having digits in non-decreasing
   order. */
#include<bits/stdc++.h>
using namespace std;
 
// Returns the required number
long long nondecdigits(long long n)
{
    /* loop to recursively check the numbers less
       than or equal to given number*/
    long long int x = 0;
    for (x=n; x>=1; x--)
    {
        int no = x;
        int prev_dig = 11;
 
        // Keep traversing digits from
        // right to left. For every digit
        // check if it is smaller than prev_dig
        bool flag = true;
        while (no != 0)
        {
            if (prev_dig < no%10)
            {
               flag = false;
               break;
            }
            prev_dig = no % 10;
            no /= 10;
        }
 
        // We found the required number
        if (flag == true)
           break;
    }
 
    return x;
}
 
// Driver program
int main()
{
    long long n = 200;
    cout << nondecdigits(n);
    return 0;
}


Java




// Java program for brute force
// approach to find largest number
// having digits in non-decreasing
// order.
import java.io.*;
 
class GFG
{
     
// Returns the required number
static int nondecdigits(int n)
{
    // loop to recursively check
    // the numbers less than or
    // equal to given number
    int x = 0;
    for (x = n; x >= 1; x--)
    {
        int no = x;
        int prev_dig = 11;
 
        // Keep traversing digits
        // from right to left. For
        // every digit check if it
        // is smaller than prev_dig
        boolean flag = true;
        while (no != 0)
        {
            if (prev_dig < no % 10)
            {
                flag = false;
                break;
            }
            prev_dig = no % 10;
            no /= 10;
        }
 
        // We found the
        // required number
        if (flag == true)
        break;
    }
 
    return x;
}
 
// Driver Code
public static void main (String[] args)
{
    int n = 200;
    System.out.println (nondecdigits(n));
}
}
 
// This code is contributed by ajit


Python3




# Python 3 program for brute force approach
# to find largest number having digits in
# non-decreasing order.
 
# Returns the required number
def nondecdigits( n):
 
    ''' loop to recursively check the numbers
    less than or equal to given number'''
    x = 0
    for x in range(n, 0, -1):
        no = x
        prev_dig = 11
 
        # Keep traversing digits from
        # right to left. For every digit
        # check if it is smaller than prev_dig
        flag = True
        while (no != 0):
            if (prev_dig < no % 10):
                flag = False
                break
             
            prev_dig = no % 10
            no //= 10
 
        # We found the required number
        if (flag == True):
            break
    return x
 
# Driver Code
if __name__=="__main__":
     
    n = 200
    print(nondecdigits(n))
 
# This code is contributed by ita_c


C#




// C# program for brute
// force approach to find
// largest number having
// digits in non-decreasing
// order.
using System;
 
class GFG
{
// Returns the required number
static int nondecdigits(int n)
{
    // loop to recursively
    // check the numbers less
    // than or equal to given
    // number
    int x = 0;
    for (x = n; x >= 1; x--)
    {
        int no = x;
        int prev_dig = 11;
 
        // Keep traversing digits
        // from right to left. For
        // every digit check if it
        // is smaller than prev_dig
        bool flag = true;
        while (no != 0)
        {
            if (prev_dig < no % 10)
            {
                flag = false;
                break;
            }
            prev_dig = no % 10;
            no /= 10;
        }
 
        // We found the
        // required number
        if (flag == true)
        break;
    }
 
    return x;
}
 
// Driver Code
static public void Main ()
{
    int n = 200;
    Console.WriteLine(nondecdigits(n));
}
}
 
// This code is contributed
// by akt_mit


PHP




<?php
// PHP program for brute
// force approach to find
// largest number having
// digits in non-decreasing
// order.
 
// Returns the required number
function nondecdigits($n)
{
     
    /* loop to recursively
       check the numbers less
       than or equal to
       given number*/
    $x = 0;
    for ($x = $n; $x >= 1; $x--)
    {
        $no = $x;
        $prev_dig = 11;
 
        // Keep traversing
        // digits from
        // right to left.
        // For every digit
        // check if it is
        // smaller than prev_dig
        $flag = true;
        while ($no != 0)
        {
            if ($prev_dig < $no%10)
            {
                $flag = false;
                break;
            }
            $prev_dig = $no % 10;
            $no /= 10;
        }
 
        // We found the
        // required number
        if ($flag == true)
        break;
    }
 
    return $x;
}
 
    // Driver Code
    $n = 200;
    echo nondecdigits($n);
     
// This code is contributed by ajt
?>


Javascript




<script>
 
// Javascript program for brute force 
// approach to find largest number
// having digits in non-decreasing
// order.    
 
// Returns the required number
function nondecdigits(n)
{
     
    // Loop to recursively check
    // the numbers less than or
    // equal to given number
    let x = 0;
    for(x = n; x >= 1; x--)
    {
        let no = x;
        let prev_dig = 11;
   
        // Keep traversing digits
        // from right to left. For
        // every digit check if it
        // is smaller than prev_dig
        let flag = true;
        while (no != 0)
        {
            if (prev_dig < no % 10)
            {
                flag = false;
                  break;
            }
            prev_dig = no % 10;
            no = Math.floor(no / 10);
        }
   
        // We found the
        // required number
        if (flag == true)
          break;
    }
    return x;
}
 
// Driver code
let n = 200;
 
document.write(nondecdigits(n));
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output: 

199

Efficient approach 
The method discussed above is not much efficient as would only give results for numbers upto 10^5, but if the number is very big such that it contains 10^5 digits. 

So, we will discuss an another method for such big numbers. 
Step 1: Store the digits of the number in array or a vector.
Step 2: Start traversing the array from the digit from rightmost position to leftmost in given number.
Step 3: If a digit is greater than the digit in the right to it, note the index of that digit in that array and decrease that digit by one.
Step 4 : Keep updating that index until you completely traverse the array accordingly as discussed in step 3.
Step 4: Set all the digits right to that index as 9 .
Step 5 : Print the array as this is the required number.

Suppose the number is 200 the digits will be 2, 0, 0. The index at which leftmost digit is greater than the right digit is index 1 (following 1-index) so the number at index 1 will be 2 – 1 = 1 and all the digits right to it will be 9. So the final array will be 1, 9, 9. And the required number will be 199.

C++




/* C++ program for efficient approach to find
   largest number having digits in non-decreasing
   order. */
#include<bits/stdc++.h>
using namespace std;
 
// Prints the largest number smaller than s and
// digits in non-decreasing order.
void nondecdigits(string s)
{
    long long m = s.size();
 
    /* array to store digits of number */
    long long a[m];
 
    /* conversion of characters of string int number */
    for (long long i=0; i<m; i++)
        a[i] = s[i] - '0';
 
    /* variable holds the value of index after which
       all digits are set 9 */
    long long level = m-1;
    for (long long i=m-1; i>0; i--)
    {
        /* Checking the condition if the digit is
           less than its left digit */
        if (a[i] < a[i-1])
        {
            a[i-1]--;
            level=i-1;
        }
    }
 
    /* If first digit is 0 no need to print it */
    if (a[0] != 0)
    {
        for (long long i=0; i<=level; i++)
            cout << a[i];
        for (long long i=level+1; i<m; i++)
            cout << "9";
    }
    else
    {
        for (long long i=1; i<level; i++)
            cout << a[i];
        for (long long i=level+1; i<m; i++)
            cout << "9";
    }
}
 
// Driver function
int main()
{
    string n = "200";
    nondecdigits(n);
    return 0;
}


Java




/* Java program for efficient approach to find
largest number having digits in non-decreasing
order. */
import java.util.*;
 
class GFG
{
     
// Prints the largest number smaller than s and
// digits in non-decreasing order.
static void nondecdigits(String s)
{
    int m = s.length();
 
    /* array to store digits of number */
    int[] a = new int[m + 1];
 
    /* conversion of characters of string int number */
    for (int i = 0; i < m; i++)
        a[i] = (int)s.charAt(i) - (int)'0';
 
    /* variable holds the value of index after which
    all digits are set 9 */
    int level = m - 1;
    for (int i = m - 1; i > 0; i--)
    {
        /* Checking the condition if the digit is
        less than its left digit */
        if (a[i] < a[i - 1])
        {
            a[i - 1]--;
            level = i - 1;
        }
    }
 
    /* If first digit is 0 no need to print it */
    if (a[0] != 0)
    {
        for (int i = 0; i <= level; i++)
            System.out.print(a[i]);
        for (int i = level + 1; i < m; i++)
            System.out.print("9");
    }
    else
    {
        for (int i = 1; i < level; i++)
            System.out.print(a[i]);
        for (int i = level + 1; i < m; i++)
            System.out.print("9");
    }
}
 
// Driver code
public static void main(String[] args)
{
    String n = "200";
    nondecdigits(n);
}
}
 
// This code is contributed by chandan_jnu


Python3




# Python3 program for efficient approach to
# find largest number having digits in
# non-decreasing order.
 
# Prints the largest number smaller than s
# and digits in non-decreasing order.
def nondecdigits(s):
    m = len(s);
 
    # array to store digits of number
    a = [0] * m;
 
    # conversion of characters of string
    # int number
    for i in range(m):
        a[i] = ord(s[i]) - ord('0');
 
    # variable holds the value of index
    # after which all digits are set 9
    level = m - 1;
    for i in range(m - 1, 0, -1):
         
        # Checking the condition if the digit
        # is less than its left digit
        if (a[i] < a[i - 1]):
            a[i - 1] -= 1;
            level = i - 1;
 
    # If first digit is 0 no need to print it */
    if (a[0] != 0):
        for i in range(level + 1):
            print(a[i], end = "");
        for i in range(level + 1, m):
            print("9", end = "");
    else:
        for i in range(1, level):
            print(a[i], end = "");
        for i in range(level + 1, m):
            print("9", end = "");
 
# Driver Code
n = "200";
nondecdigits(n);
 
# This code is contributed by mits


C#




/* C# program for efficient approach to find
largest number having digits in non-decreasing
order. */
using System;
 
class GFG
{
     
// Prints the largest number smaller than s and
// digits in non-decreasing order.
static void nondecdigits(string s)
{
    int m = s.Length;
 
    /* array to store digits of number */
    int[] a = new int[m + 1];
 
    /* conversion of characters of string int number */
    for (int i = 0; i < m; i++)
        a[i] = (int)s[i] - (int)'0';
 
    /* variable holds the value of index after which
    all digits are set 9 */
    int level = m - 1;
    for (int i = m - 1; i > 0; i--)
    {
        /* Checking the condition if the digit is
        less than its left digit */
        if (a[i] < a[i - 1])
        {
            a[i - 1]--;
            level = i - 1;
        }
    }
 
    /* If first digit is 0 no need to print it */
    if (a[0] != 0)
    {
        for (int i = 0; i <= level; i++)
            Console.Write(a[i]);
        for (int i = level + 1; i < m; i++)
            Console.Write("9");
    }
    else
    {
        for (int i = 1; i < level; i++)
            Console.Write(a[i]);
        for (int i = level + 1; i < m; i++)
            Console.Write("9");
    }
}
 
// Driver code
static void Main()
{
    string n = "200";
    nondecdigits(n);
}
}
 
// This code is contributed by chandan_jnu


PHP




<?php
/* PHP program for efficient
approach to find largest number
having digits in non-decreasing
order. */
 
// Prints the largest number
// smaller than s and digits
// in non-decreasing order.
function nondecdigits($s)
{
    $m = strlen($s);
 
    /* array to store
    digits of number */
    $a[$m] = 0;
 
    /* conversion of characters
    of string int number */
    for ($i = 0; $i < $m; $i++)
        $a[$i] = $s[$i] - '0';
 
    /* variable holds the
    value of index after
    which all digits are set 9 */
    $level = $m - 1;
    for ($i = $m - 1; $i > 0; $i--)
    {
        /* Checking the condition
        if the digit is less than
        its left digit */
        if ($a[$i] < $a[$i - 1])
        {
            $a[$i - 1]--;
            $level = $i - 1;
        }
    }
 
    /* If first digit is 0
    no need to print it */
    if ($a[0] != 0)
    {
        for ($i = 0;
             $i <= $level; $i++)
            echo $a[$i];
        for ($i = $level + 1;
             $i < $m; $i++)
            echo "9";
    }
    else
    {
        for ($i = 1; $i < $level; $i++)
            echo $a[$i];
        for ($i = $level + 1;
             $i < $m; $i++)
                echo "9";
    }
}
 
// Driver Code
$n = "200";
nondecdigits($n);
 
// This code is contributed
// by ajit
?>


Javascript




<script>
 
// Javascript program for efficient approach
// to find largest number having digits in
// non-decreasing order.
    
// Prints the largest number smaller than
// s and digits in non-decreasing order.
function nondecdigits(s)
{
    var m = s.length;
 
    // Array to store digits of number
    var a = Array.from({length: m + 1}, (_, i) => 0);
 
    // Conversion of characters of string var number
    for(i = 0; i < m; i++)
        a[i] = s.charAt(i).charCodeAt(0) -
                       '0'.charCodeAt(0);
 
    // Variable holds the value of index
    // after which all digits are set 9
    var level = m - 1;
    for(i = m - 1; i > 0; i--)
    {
         
        // Checking the condition if the digit is
        // less than its left digit
        if (a[i] < a[i - 1])
        {
            a[i - 1]--;
            level = i - 1;
        }
    }
 
    // If first digit is 0 no need to print it
    if (a[0] != 0)
    {
        for(i = 0; i <= level; i++)
            document.write(a[i]);
        for(i = level + 1; i < m; i++)
            document.write("9");
    }
    else
    {
        for(i = 1; i < level; i++)
            document.write(a[i]);
        for(i = level + 1; i < m; i++)
            document.write("9");
    }
}
 
// Driver code
var n = "200";
nondecdigits(n);
 
// This code is contributed by Princi Singh
 
</script>


Output: 

199

Time Complexity Time complexity is O(d) where d is no. of digits in the number.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads