## Summary

We need to find the next lexicographic permutation of the given list of numbers than the number formed by the given array.

## Solution

#### Approach 1: Brute Force

Algorithm

In this approach, we find out every possible permutation of list formed by the elements of the given array and find out the permutation which is just larger than the given one. But this one will be a very naive approach, since it requires us to find out every possible permutation which will take really long time and the implementation is complex. Thus, this approach is not acceptable at all. Hence, we move on directly to the correct approach.

Complexity Analysis

• Time complexity : . Total possible permutations is .
• Space complexity : . Since an array will be used to store the permutations.

#### Approach 2: Single Pass Approach

Algorithm

First, we observe that for any given sequence that is in descending order, no next larger permutation is possible. For example, no next permutation is possible for the following array: [9, 5, 4, 3, 1]

We need to find the first pair of two successive numbers and , from the right, which satisfy . Now, no rearrangements to the right of can create a larger permutation since that subarray consists of numbers in descending order. Thus, we need to rearrange the numbers to the right of including itself.

Now, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number with the number which is just larger than itself among the numbers lying to its right section, say .

We swap the numbers and . We now have the correct number at index . But still the current permutation isn't the permutation that we are looking for. We need the smallest permutation that can be formed by using the numbers only to the right of . Therefore, we need to place those numbers in ascending order to get their smallest permutation.

But, recall that while scanning the numbers from the right, we simply kept decrementing the index until we found the pair and where, . Thus, all numbers to the right of were already sorted in descending order. Furthermore, swapping and didn't change that order. Therefore, we simply need to reverse the numbers following to get the next smallest lexicographic permutation.

The following animation will make things clearer:

Complexity Analysis

• Time complexity : . In worst case, only two scans of the whole array are needed.

• Space complexity : . No extra space is used. In place replacements are done.