Understanding the Problem
We are given an array of integers that represents a permutation of numbers. Our goal is to find the next permutation in lexicographical (dictionary) order. If such a permutation is not possible (i.e., the given permutation is the highest possible), we return the lowest permutation by sorting the array.
Think of listing all permutations in sorted order — we want to return the one that comes immediately after the current array.
Step-by-Step Plan with Example
Let's take the example [1, 2, 3]
. Here's how we solve it:
Step 1: Find the Pivot
Scan the array from right to left and find the first number that is smaller than its next number. This is our pivot. In our example, 2 is the pivot (since 2 < 3).
Step 2: Find the Successor
Now, from the right side again, find the first number that is greater than the pivot. In our case, 3 is greater than 2.
Step 3: Swap the Pivot and Successor
Swap 2 and 3. Now the array becomes [1, 3, 2]
.
Step 4: Reverse the Suffix
Finally, reverse the part of the array that comes after the pivot's original index. But here, it's already just a single element (2), so no actual change is needed.
The final result is [1, 3, 2]
— the next permutation!
Edge Case 1: Last Permutation Already
If the array is in descending order, like [3, 2, 1]
, then it is the highest possible permutation. There is no "next" permutation.
In this case, we simply reverse the array to get the lowest permutation: [1, 2, 3]
.
Edge Case 2: Duplicates Present
The same logic works even if the array contains duplicates. For example, take [1, 1, 5]
:
- Find pivot → first 1
- Find successor → 5
- Swap →
[1, 5, 1]
- Reverse the suffix → remains
[1]
Final result: [1, 5, 1]
Edge Case 3: One or Zero Elements
- If the array has only one element, e.g.,
[7]
, no rearrangement is possible. We return the same array.
- If the array is empty, we return it as-is.
Summary
This approach works efficiently in O(n) time with no extra space. The key idea is:
- Find a pivot (first dip from right)
- Find the next greater element to pivot (successor)
- Swap them
- Reverse the suffix
This gives us the next permutation in place without generating all possible permutations.
Comments
Loading comments...