The goal of this problem is to find the next permutation in dictionary (lexicographical) order. Think of all permutations of the array elements being sorted — your task is to move to the very next one in that sorted list.
Let’s discuss how this works and what outcomes we may expect, depending on the input.
🧩 Case 1: Normal Next Permutation Exists
Suppose the array is not in the highest possible order. We can still find a next greater permutation. To do that:
- We look from right to left and find the first element that is smaller than its right neighbor. This element is our pivot.
- Then we look again from the right and find the smallest element that is larger than the pivot — and we swap them.
- Finally, we reverse the subarray after the pivot to get the smallest possible arrangement following the pivot.
This gives us the next greater permutation.
Case 2: Already the Last Permutation
If the array is in descending order (like [3, 2, 1]), it is already the last permutation. There's no greater permutation possible. In this case, the next permutation is just the smallest one — so we sort the array in ascending order.
🔄 Case 3: Duplicates Present
Even if the array has repeated numbers, the same logic applies. For example, in [1, 1, 5], the pivot is the first 1, and the next greater element is 5. We swap them and reverse the rest to get [1, 5, 1].
Case 4: Single Element or Empty Array
- For a single element array, there is no rearrangement possible. So the array remains the same.
- For an empty array, we return it as-is. There’s no permutation to perform.
Summary
This optimal solution works in linear time and does not use extra space. It’s based on the observation that the next permutation is formed by modifying the suffix of the array in a smart way. By finding a pivot, swapping, and reversing a part of the array, we efficiently jump to the next valid permutation.