LeetCode 31: Next Permutation Solution
Master LeetCode problem 31 (Next Permutation), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
31. Next Permutation
Problem Explanation
Explanation
To find the next lexicographically greater permutation of an array, we can follow these steps:
- Traverse the array from right to left to find the first element (let's call it
pivot) that is smaller than the element to its right. - If such a
pivotexists, find the smallest element to the right ofpivotthat is greater thanpivot. Swappivotwith this element. - Reverse the subarray to the right of the
pivotto get the next permutation. - If no such
pivotexists, it means the array is in descending order, so we reverse the entire array to get the lowest possible order (ascending order).
Time complexity: O(n) where n is the length of the array. Space complexity: O(1) as no extra memory is used.
Solution Code
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.length - 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void reverse(int[] nums, int start) {
int end = nums.length - 1;
while (start < end) {
swap(nums, start, end);
start++;
end--;
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 31 (Next Permutation)?
This page provides optimized solutions for LeetCode problem 31 (Next Permutation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 31 (Next Permutation)?
The time complexity for LeetCode 31 (Next Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 31 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 31 in Java, C++, or Python.