Next Permutation
Last Updated :
13 Apr, 2024
Given an array arr[] of size N, the task is to print the lexicographically next greater permutation of the given array. If there does not exist any greater permutation, then print the lexicographically smallest permutation of the given array.
Examples:
Input: N = 6, arr = {1, 2, 3, 6, 5, 4}
Output: {1, 2, 4, 3, 5, 6}
Explanation: The next permutation of the given array is {1, 2, 4, 3, 5, 6}.
Input: N = 3, arr = {3, 2, 1}
Output: {1, 2, 3}
Explanation: As arr[] is the last permutation.Â
So, the next permutation is the lowest one.
Let’s first understand what is lexicographical order in the above-given program.
We have to check that the order of the array sequence is greater than the previous array sequence. The output will be just larger sequence of the array.
Brute Force Approach :
- Find all possible permutations of the given array.
- Print the Next permutation right after the er given input sequence.
Time Complexity: O(N * N!), N represents the number of elements present in the input sequence. represent all possible permutation. Therefore, It takes the time complexity O(N*N!).
Auxiliary Space: O(N), for storing the permutation in some data structure.
Using C++ in-build function:
C++ provides an in-built function called next_permutation(), that return directly lexicographically in the next greater permutation of the input.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the next permutation
void nextPermutation(vector<int>& arr)
{
next_permutation(arr.begin(),arr.end());
}
// Driver code
int main()
{
// Given input array
vector<int> arr = { 1, 2, 3, 6, 5, 4 };
// Function call
nextPermutation(arr);
// Printing the answer
for (auto i : arr) {
cout << i << " ";
}
return 0;
}
Java
import java.util.Arrays;
public class NextPermutation {
public static void GFG(int[] arr) {
int i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
// If no such index exists, the entire array is in descending order so reverse it
if (i == -1) {
reverse(arr, 0, arr.length - 1);
return;
}
// Find the largest index j greater than i such that arr[i] < arr[j]
int j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Reverse the suffix starting from index i + 1
reverse(arr, i + 1, arr.length - 1);
}
// Function to reverse the subarray from index start to end
public static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
// Given input array
int[] arr = {1, 2, 3, 6, 5, 4};
GFG(arr);
// Printing the answer
System.out.println(Arrays.toString(arr));
}
}
Python3
# Function to find the next permutation
def next_permutation(arr):
# Find the first element from the right which is smaller than the element next to it
i = len(arr) - 2
while i >= 0 and arr[i] >= arr[i + 1]:
i -= 1
if i >= 0:
# Find the smallest element from the right which is greater than arr[i]
j = len(arr) - 1
while arr[j] <= arr[i]:
j -= 1
# Swap arr[i] and arr[j]
arr[i], arr[j] = arr[j], arr[i]
# Reverse the elements after index i to get the next permutation
left, right = i + 1, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# Driver code
if __name__ == "__main__":
# Given input array
arr = [1, 2, 3, 6, 5, 4]
# Function call
next_permutation(arr)
# Printing the answer
print(*arr)
JavaScript
function GFG(arr) {
let i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
// If no such index exists, the entire array is in the descending order so reverse it
if (i === -1) {
arr.reverse();
return;
}
// Find the largest index j greater than i such that arr[i] < arr[j]
let j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
// Swap arr[i] and arr[j]
[arr[i], arr[j]] = [arr[j], arr[i]];
// Reverse the suffix starting from index i + 1
let left = i + 1, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
// Driver code
(() => {
// Given input array
let arr = [1, 2, 3, 6, 5, 4];
GFG(arr);
// Printing the answer
console.log(arr.join(" "));
})();
Next Permutation in linear time complexity:
Illustration:Â
Let’s try some examples to see if we can recognize some patterns.Â
[3, 1, 3] = next greater number is 331
[5, 1, 3] = next greater number is 531
[1, 2, 3] = next greater number is 132
[1, 3, 5, 4] = next greater number is 1435
[3, 2, 1] = we can’t form a number greater than the current number from all the possible permutations
So, it is clear that to get the next permutation we will have to change the number in a position which is as right as possible. Each permutation (except the very first) has a increasing suffix. Now if we change the pattern from the pivot point (where the increasing suffix breaks) to its next possible lexicographic representation we will get the next greater permutation.
To understand how to change the pattern from pivot, see the below image:
Observation of Next permutation:Â
Illustration of next_permutation
Follow the steps below to implement the above observation:
- Iterate over the given array from end and find the first index (pivot) which doesn’t follow property of non-increasing suffix, (i.e, Â arr[i] < arr[i + 1]).
- Check if pivot index does not existÂ
- This means that the given sequence in the array is the largest as possible. So, swap the complete array.
- Otherwise, Iterate the array from the end and find for the successor of pivot in suffix.
- Swap the pivot and successor
- Minimize the suffix part by reversing the array from pivot + 1 till N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the next permutation
void nextPermutation(vector<int>& arr)
{
int n = arr.size(), i, j;
// Find for the pivot element.
// A pivot is the first element from
// end of sequenc ewhich doesn't follow
// property of non-increasing suffix
for (i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
break;
}
}
// Check if pivot is not found
if (i < 0) {
reverse(arr.begin(), arr.end());
}
// if pivot is found
else {
// Find for the successor of pivot in suffix
for (j = n - 1; j > i; j--) {
if (arr[j] > arr[i]) {
break;
}
}
// Swap the pivot and successor
swap(arr[i], arr[j]);
// Minimise the suffix part
reverse(arr.begin() + i + 1, arr.end());
}
}
// Driver code
int main()
{
// Given input array
vector<int> arr = { 1, 2, 3, 6, 5, 4 };
// Function call
nextPermutation(arr);
// Printing the answer
for (auto i : arr) {
cout << i << " ";
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to find the next permutation
static void nextPermutation(int[] arr)
{
int n = arr.length, i, j;
// Find for the pivot element.
// A pivot is the first element from
// end of sequencewhich doesn't follow
// property of non-increasing suffix
for (i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
break;
}
}
// Check if pivot is not found
if (i < 0) {
reverse(arr, 0, arr.length - 1);
}
// if pivot is found
else {
// Find for the successor of pivot in suffix
for (j = n - 1; j > i; j--) {
if (arr[j] > arr[i]) {
break;
}
}
// Swap the pivot and successor
swap(arr, i, j);
// Minimise the suffix part
reverse(arr, i + 1, arr.length - 1);
}
}
static void reverse(int[] arr, int start, int end)
{
while (start < end) {
swap(arr, start, end);
start++;
end--;
}
}
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args)
{
// Given input array
int[] arr = new int[] { 1, 2, 3, 6, 5, 4 };
// Function call
nextPermutation(arr);
// Printing the answer
for (int i : arr) {
System.out.print(i + " ");
}
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python code to implement the above approach
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
# Function to find the next permutation
def nextPermutation(arr):
n = len(arr)
i = len(arr)-2
j = 0
# Find for the pivot element.
# A pivot is the first element from
# end of sequencewhich doesn't follow
# property of non-increasing suffix
while i>=0:
if arr[i]<arr[i+1]:
break
i=i-1
# Check if pivot is not found
if (i < 0):
arr.reverse()
# if pivot is found
else:
# Find for the successor of pivot in suffix
for j in range(n-1, i, -1):
if (arr[j] > arr[i]):
break
# Swap the pivot and successor
swapPositions(arr, i, j)
# Minimise the suffix part
# initializing range
strt, end = i+1, len(arr)
# Third arg. of split with -1 performs reverse
arr[strt:end] = arr[strt:end][::-1]
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 6, 5, 4]
# Function call
nextPermutation(arr)
# Printing the answer
for i in arr:
print(i, end=" ")
# This code is contributed by Rohit Pradhan
C#
// Include namespace system
using System;
public class GFG
{
// Function to find the next permutation
public static void nextPermutation(int[] arr)
{
var n = arr.Length;
int i;
int j;
// Find for the pivot element.
// A pivot is the first element from
// end of sequencewhich doesn't follow
// property of non-increasing suffix
for (i = n - 2; i >= 0; i--)
{
if (arr[i] < arr[i + 1])
{
break;
}
}
// Check if pivot is not found
if (i < 0)
{
GFG.reverse(arr, 0, arr.Length - 1);
}
else
{
// Find for the successor of pivot in suffix
for (j = n - 1; j > i; j--)
{
if (arr[j] > arr[i])
{
break;
}
}
// Swap the pivot and successor
GFG.swap(arr, i, j);
// Minimise the suffix part
GFG.reverse(arr, i + 1, arr.Length - 1);
}
}
public static void reverse(int[] arr, int start, int end)
{
while (start < end)
{
GFG.swap(arr, start, end);
start++;
end--;
}
}
public static void swap(int[] arr, int i, int j)
{
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void Main(String[] args)
{
// Given input array
int[] arr = new int[]{1, 2, 3, 6, 5, 4};
// Function call
GFG.nextPermutation(arr);
// Printing the answer
foreach (int i in arr)
{
Console.Write(i.ToString() + " ");
}
}
}
// This code is contributed by aadityaburujwale.
Javascript
// javascript code implementation
// Function to find the next permutation
function nextPermutation(arr)
{
let n = arr.length, i, j;
// Find for the pivot element.
// A pivot is the first element from
// end of sequencewhich doesn't follow
// property of non-increasing suffix
for (i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
break;
}
}
// Check if pivot is not found
if (i < 0) {
arr.reverse();
}
// if pivot is found
else {
// Find for the successor of pivot in suffix
for (j = n - 1; j > i; j--) {
if (arr[j] > arr[i]) {
break;
}
}
// Swap the pivot and successor
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// Minimise the suffix part
let arr1 = arr.slice(i+1, n);
arr1.reverse();
arr.splice(i+1, n, ...arr1);
}
}
// Driver code
// Given input array
let arr = [ 1, 2, 3, 6, 5, 4 ];
// Function call
nextPermutation(arr);
// Printing the answer
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// this code is contributed by ksam24000
Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...