Monday, May 12, 2014

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

Solution :

We first find the digit starting from unit's place that is less than the preceding digit. In an Array A start with i = n-2. compare A[n-2] with A[n-1] and keep decrementing i till we find A[i]
For eg: in 1,3,2 we get i=0;
In another example 1,2,4,3,1,1 we get i =1. Hence the value 0 to i-1 need not be disturbed. We now need to find the next permutation of number starting from i.
We now need to find the next digit which is the least digit greater than A[i].
For that we move from the end of array and stop at k=3 (A[k]=3). We now swap A[i] and A[k]. So the array now is 1,3,4,2,1,1. Now we reverse the array starting from i+1. We now get 1,3,1,1,2,4 which is the next permutation.



Code: 

No comments:

Post a Comment