Type like pro

Index

Make larger number

Make larger number

Problem

Given a number whose digits are unique, find the next larger number that can be formed with those digits.

Solution

If all the digits are in decreasing order from left to right, then no larger number is possible as that is the largest number possible with those digits. If they are not in that order then a larger number is possible. We need to find the right most digit which is larger than its immediate left. Then we can bring the larger digit in place of the smaller digit and then arrange the remaining digits in increasing order. For example, if the number is 3784, 8 is the right most digit which is larger than it's left (7). We first replace 7 with 8, so it becomes 38.., then arrange the 7 and 4 in increasing order. so it becomes 3847

Code