Leetcode Problem 31. Next Permutation
31. Next Permutation
AI Mock Interview
Leetcode Solutions
Single Pass Approach
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Start from the end of the array and move backwards to find the first pair where
nums[i] > nums[i-1]
.
If such a pair is found, search for the smallest number greater than
nums[i-1]
to the right of
nums[i-1]
and swap them.
Reverse the subarray to the right of
nums[i-1]
to get the next permutation.
If no such pair is found, the entire array is in descending order, and we simply reverse the whole array to get the smallest permutation.
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...