I knew the algorithm from somewhere but blanked on the exact steps mid-explanation.
Start by explaining the three-step algorithm: find the pivot (first decreasing element from the right), swap it with the smallest larger element to its right, then reverse the suffix to get the next permutation. If no pivot exists, reverse the entire array to get the smallest permutation. Emphasize that this achieves O(n) time and O(1) space by modifying the array in-place.
Pro tip: Mention that this is the exact algorithm used in C++'s std::next_permutation and Python's itertools.permutations, showing you understand real-world implementations. Also, clarify that the reverse step is crucial because the suffix is already in non-increasing order, so reversing it yields the smallest possible arrangement.
Traverse the array from right to left to find the first element that is smaller than its right neighbor. This element is the pivot. If no such element exists, the array is in descending order, so reverse the entire array and return.
From the right, find the first element that is greater than the pivot. This element is the smallest element greater than the pivot in the suffix (since the suffix is non-increasing).
Swap the pivot with the successor. This ensures the next permutation is lexicographically greater.
Reverse the subarray to the right of the pivot's original position. Since the suffix was non-increasing, reversing it makes it non-decreasing, which is the smallest possible arrangement for that suffix.
If no pivot was found in step 1, reverse the entire array to get the smallest permutation (ascending order).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.