I knew the algorithm in theory but fumbled the edge cases badly.
Start by clarifying the problem and edge cases, then explain the three-step algorithm: find the pivot, find the successor, and reverse the suffix. Emphasize that the algorithm works in-place with O(1) extra space and O(n) time, and walk through an example to demonstrate correctness.
Pro tip: Mention that this algorithm is the same as the one used in C++'s std::next_permutation, and that it's a common interview question at top tech companies. Also, explicitly state the time and space complexity before writing code to show you think about efficiency.
Confirm the problem details: in-place, constant extra memory, and what to do if no next permutation exists. Discuss edge cases like empty array, single element, and already descending array.
Scan from right to left to find the first index i where nums[i] < nums[i+1]. If no such index exists, the array is in descending order, so reverse the entire array to get the smallest permutation.
From the right, find the first element nums[j] that is greater than nums[i]. Swap nums[i] and nums[j].
Reverse the subarray from i+1 to the end to get the smallest possible suffix, ensuring the next permutation is the immediate next in lexicographic order.
State that the algorithm runs in O(n) time and O(1) space. Walk through a small example to verify correctness and discuss potential pitfalls.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.