Algorithm Day100 - Next Permutation
🧩 Problem
LeetCode 31 - Next Permutation
Implement the next lexicographical permutation of the given integer array nums.
If such arrangement is not possible, rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Example:
1 | Input: nums = [1,2,3] |
💡 Idea
To get the next lexicographically larger permutation, we follow three steps:
Find the first decreasing element (pivot) from the right side where
nums[i] < nums[i+1].
If no such index exists, it means the array is in descending order → reverse it directly.Find the smallest element greater than
nums[i]to the right of it, saynums[j].Swap
nums[i]andnums[j], then reverse the subarray fromi+1to the end.
This ensures the next immediate permutation is achieved.
💻 Java Code
1 | class Solution { |
🧠 Complexity
- Time: O(n) — One pass to find pivot, one to reverse.
- Space: O(1) — In-place manipulation.
🏁 Summary
The key insight is recognizing the first decreasing pair from the right and making the minimal change to reach the next permutation.
This elegant algorithm is widely used in combinatorial generation and backtracking problems.