Solution #1:
Algorithm:
- Move from right -> left and stop when the current digit is greater than the next one, let's call this point, 'hotspot'.
- Sort all the digits from hotspot till the end of the number in increasing order.
- Swap the digit on the left of the 'hotspot' with the last digit of the new number.
e.g.
5784321
hotspot: 8
after sorting: 5712348
after swapping: 5812347
Here is the code,
Algorithm:
- Move from right -> left and stop when the current digit is greater than the next one, let's call this point, 'hotspot'.
- Sort all the digits from hotspot till the end of the number in increasing order.
- Swap the digit on the left of the 'hotspot' with the last digit of the new number.
e.g.
5784321
hotspot: 8
after sorting: 5712348
after swapping: 5812347
Here is the code,
void nextLarge(char* num) { int len = strlen(num); int i; //decrement i till digits are increasing from right to left for(i=len-1; num[i] < num[i-1]; i--) { //return if the digits are sorted in decreasing //order, number is already the largest. if(i == 1) return; } //sort everything from hotspot till the end sort(num, i, len-1); //swap digit before hotspot with the last one swap(&(num[i-1]), &(num[len-1])); } int main() { char num[20] = {0, }; sprintf(num, "%s", "5417962"); nextLarge(num); printf("%s\n", num); return 0; }
4 comments:
You could use counting sort to solve this in linear time. Better for much longer numbers.
I couldn't Get it working for 21765 because I expect the next number as 25176 but it gives me 27561.
Nice solution in C#.
Complexity O(n)
http://onestopinterviewprep.blogspot.com/2014/04/find-next-higher-number-with-same-digits.html
This does not work for all cases.
Like 2641
Algo can be this:
1. we searched for digit smaller than 1 to the left, we din't get any.
2. Moved to the next digit i.e. 4 compare it with the left digits 2 is less so we swapped we get 4621
3. Now sort the digits after the swapped final index in increasing order from left to right. we get 4126
Post a Comment