Leetcode Problem 31. Next Permutation

31. Next Permutation

Leetcode Solutions

Single Pass Approach

  1. Start from the end of the array and move backwards to find the first pair where nums[i] > nums[i-1].
  2. 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.
  3. Reverse the subarray to the right of nums[i-1] to get the next permutation.
  4. 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.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...