Tutorialspoint
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.
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].
Constraints
  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 100
  • The replacement must be in-place
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysWiproKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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].

Steps to solve by this approach:

 Step 1: Start from the right and find the first pair of adjacent elements where the left one is smaller than the right one.
 Step 2: If no such pair exists, the array is in descending order, so reverse it to get the smallest permutation.
 Step 3: Find the smallest element to the right of the pivot that is still larger than the pivot.
 Step 4: Swap the pivot with this element to ensure we get the next larger permutation.
 Step 5: Reverse all elements to the right of the original pivot position to get the smallest arrangement.
 Step 6: This ensures we get the next lexicographically greater permutation.
 Step 7: Handle edge cases like single element arrays or empty arrays.

Submitted Code :