Given a long integer, return the smallest(magnitude) integer permutation of that number.
Input : 5468001 Output : 1004568 Input : 5341 Output : 1345
Question Source : GE digital Interview Experience | Set 6
We have already discussed a solution in below post.
In this post, a different approach is discussed.
Approach : As number is long, store the number as string, sort the string, if there is no leading zero, return this string, if there is any leading zero, swap first element of string with first non-zero element of string, and return the string.
Below is the implementation of above approach :
Since character set is limited (‘0’ to ‘9’), we can write our own sort method that works in linear time (by counting frequencies of all characters)
This article is contributed by Mandeep Singh. 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.
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
- Smallest non-zero substring which has any permutation divisible by 2^K
- Find the smallest number whose digits multiply to a given number n
- Find smallest number K such that K % p = 0 and q % K = 0
- Lexicographically smallest permutation with no digits at Original Index
- Find the kth smallest number with sum of digits as m
- Find smallest number n such that n XOR n+1 equals to given k.
- Given a number, find the next smallest palindrome
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Find smallest positive number Y such that Bitwise AND of X and Y is Zero
- Find Nth smallest number that is divisible by 100 exactly K times
- Find the k-th smallest divisor of a natural number N
- Find kth smallest number in range [1, n] when all the odd numbers are deleted
- Find the smallest positive number which can not be represented by given digits