Saturday, January 30, 2016

Find Next Higher Number With Same Digits

Question: Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243.
Solution 1: The brute-force method is to generate the numbers with all digit permutations and consider all the higher numbers than the given number and return the minimum number from those higher numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int findNext(int n)
    {
        int nextNum = INT_MAX;
        String nStr = Integer.toString(n);
         
        for(String perm : permutations(nStr)) {
            int pNum = Integer.valueOf(perm);
            if(pNum>n){
                nextNum = Math.min(pNum, nextNum);
            }          
        }
        if(nextNum == INT_MAX) {
            return -1;
        }
        else {
            return nextNum;
        }
    }
Solution 2: Let’s visualize a better solution using an example, the given number is 12543 and the resulting next higher number should be 13245. We scan the digits of the given number starting from the tenths digit (which is 4 in our case) going towards left. At each iteration we check the right digit of the current digit we’re at, and if the value of right is greater than current we stop, otherwise we continue to left. So we start with current digit 4, right digit is 3, and 4>=3 so we continue. Now current digit is 5, right digit is 4, and 5>= 4, continue. Now current is 2, right is 5, but it’s not 2>=5, so we stop. The digit 2 is our pivot digit. From the digits to the right of 2, we find the smallest digit higher than 2, which is 3. This part is important, we should find the smallest higher digit for the resulting number to be precisely the next higher than original number. We swap this digit and the pivot digit, so the number becomes 13542. Pivot digit is now 3. We sort all the digits to the right of the pivot digit in increasing order, resulting in 13245. This is it, here’s the code:
Note that if the digits of the given number is monotonically increasing from right to left, like 43221 then we won’t perform any operations, which is what we want because this is the highest number obtainable from these digits. There’s no higher number, so we return the given number itself. The same case occurs when the number has only a single digit, like 7. We can’t form a different number since there’s only a single digit.

No comments:

Post a Comment