
Problem
Solution
Submissions
Next Permutation
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to find the next lexicographically greater permutation of an array of integers. 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]
- Output: [1, 3, 2]
- Explanation:
- Step 1: The next permutation of [1, 2, 3] is [1, 3, 2].
- Step 2: This is the next lexicographically greater arrangement.
- Step 3: We swap 2 and 3 to get the result.
- Step 1: The next permutation of [1, 2, 3] is [1, 3, 2].
Example 2
- Input: nums = [3, 2, 1]
- Output: [1, 2, 3]
- Explanation:
- Step 1: [3, 2, 1] is the largest permutation.
- Step 2: No next greater permutation exists.
- Step 3: Return the smallest permutation [1, 2, 3].
- Step 1: [3, 2, 1] is the largest permutation.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 100
- The replacement must be in-place
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Find the largest index i such that nums[i] < nums[i + 1].
- If no such index exists, reverse the entire array.
- Find the largest index j such that nums[i] < nums[j].
- Swap nums[i] and nums[j].
- Reverse the suffix starting at nums[i + 1].