There are some natural number whose all permutation is greater than or equal to that number eg. 123, whose all the permutation (123, 231, 321) are greater than or equal to 123.
Given a natural number n, the task is to count all such number from 1 to n.
Input : n = 15. Output : 14 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15 are the numbers whose all permutation is greater than the number itself. So, output 14. Input : n = 100. Output : 54
A simple solution is to run a loop from 1 to n and for every number check if its digits are in non-decreasing order or not.
An efficient solution is based on below observations.
Observation 1: From 1 to 9, all number have this property. So, for n <= 9, output n.
Observation 2: The number whose all permutation is greater than or equal to that number have all their digits in increasing order.
The idea is to push all the number from 1 to 9. Now, pop the top element, say topel and try to make number whose digits are in increasing order and the first digit is topel. To make such numbers, the second digit can be from topel%10 to 9. If this number is less than n, increment the count and push the number in the stack, else ignore.
Below is the implementation of this approach:
Time Complexity : O(x) where x is number of elements printed in output.
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count numbers with difference between number and its digit sum greater than specific value
- Find the count of natural Hexadecimal numbers of size N
- Count Numbers with N digits which consists of even number of 0’s
- Count the number of digits of palindrome numbers in an array
- Count of Numbers in Range where first digit is equal to last digit of the number
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Find smallest permutation of given number
- Check if any permutation of a number is divisible by 3 and is Palindromic
- Least Greater number with same digit sum
- Find next greater number with same set of digits
- Print next greater number of Q queries
- Largest number not greater than N all the digits of which are odd
- Largest even digit number not greater than N
- Next greater number on the basis of precedence of digits
- Nearest greater number by interchanging the digits