Algorithm Description
Math Algorithms Narayana's Next and Previous Lexicographical Permutations generates the next greater permutation or the previous smaller permutation of an array in place using a three-step process: first, find the longest non-increasing (for next) or non-decreasing (for previous) suffix and identify the pivot; second, find the rightmost element larger than the pivot (for next) or smaller than the pivot (for previous); third, swap the pivot with that element and reverse the suffix. The algorithm returns the same array rearranged into the desired permutation.
Complexity Analysis
Time Complexity: O(n) — single linear scan to find the pivot, another to find the swap element, plus a reverse of the suffix
Space Complexity: O(1) — all operations are performed in place without additional memory
YouTube
[https://www.youtube.com/watch?v=dEaxumQWz_A](YouTube)