Given an array of integers arr[] representing a permutation (i.e., all elements are unique and arranged in some order), find the next lexicographically greater permutation by rearranging the elements of the array.
If such a permutation does not exist (i.e., the array is the last possible permutation), rearrange the elements to form the lowest possible order (i.e., sorted in ascending order).
Examples:
Input: arr[] = [2, 4, 1, 7, 5, 0]
Output: [2, 4, 5, 0, 1, 7]
Explanation: The next lexicographically greater arrangement of the elements in the array arr[] is [2, 4, 5, 0, 1, 7].
Input: arr[] = [3, 2, 1]
Output: [1, 2, 3]
Explanation: This is the last permutation, so we return the lowest possible permutation (ascending order).
Input: arr[] = [1, 3, 5, 4, 2]
Output: [1, 4, 2, 3, 5]
Explanation: The next lexicographically greater arrangement of the elements in the array arr[] is [1, 4, 2, 3, 5].
[Naive Approach] Generate All Permutations - O(n! * n) Time and O(n! * n) Space
The idea is that we would first generate all possible permutations of a given array and sort them. Once sorted, we locate the current permutation within this list. The next permutation is simply the next arrangement in the sorted order. If the current arrangement is the last in the list then display the first permutation (smallest permutation).
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void generatePermutations(vector<vector<int>> &res,
vector<int> &arr, int idx) {
// Base case: if idx reaches the end of array
if (idx == arr.size() - 1) {
res.push_back(arr);
return;
}
// Generate all permutations by swapping
for (int i = idx; i < arr.size(); i++) {
swap(arr[idx], arr[i]);
// Recur for the next index
generatePermutations(res, arr, idx + 1);
// Backtrack to restore original array
swap(arr[idx], arr[i]);
}
}
// Function to find the next permutation
void nextPermutation(vector<int>& arr) {
vector<vector<int>> res;
// Generate all permutations
generatePermutations(res, arr, 0);
// Sort all permutations lexicographically
sort(res.begin(), res.end());
// Find the current permutation index
for (int i = 0; i < res.size(); i++) {
// If current permutation matches input
if (res[i] == arr) {
// If it's not the last permutation
if (i < res.size() - 1) {
arr = res[i + 1];
}
// If it's the last permutation
else {
arr = res[0];
}
break;
}
}
}
int main() {
vector<int> arr = {2, 4, 1, 7, 5, 0};
nextPermutation(arr);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Java
import java.util.*;
class GfG {
// Function to generate all possible permutations
static void generatePermutations(List<List<Integer>> res,
int[] arr, int idx) {
// Base case: if idx reaches the end of array
if (idx == arr.length - 1) {
List<Integer> temp = new ArrayList<>();
for (int x : arr) temp.add(x);
res.add(temp);
return;
}
// Generate all permutations by swapping
for (int i = idx; i < arr.length; i++) {
swap(arr, idx, i);
// Recur for the next index
generatePermutations(res, arr, idx + 1);
// Backtrack to restore original array
swap(arr, idx, i);
}
}
static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
// Function to find the next permutation
static void nextPermutation(int[] arr) {
List<List<Integer>> res = new ArrayList<>();
// Generate all permutations
generatePermutations(res, arr, 0);
// Sort all permutations lexicographically
Collections.sort(res, (a, b) -> {
for (int i = 0; i < a.size(); i++) {
if (!a.get(i).equals(b.get(i))) {
return a.get(i) - b.get(i);
}
}
return 0;
});
// Find the current permutation index
for (int i = 0; i < res.size(); i++) {
// If current permutation matches input
boolean match = true;
for (int j = 0; j < arr.length; j++) {
if (arr[j] != res.get(i).get(j)) {
match = false;
break;
}
}
if (match) {
// If it's not the last permutation
if (i < res.size() - 1) {
for (int j = 0; j < arr.length; j++) {
arr[j] = res.get(i + 1).get(j);
}
}
// If it's the last permutation
else {
for (int j = 0; j < arr.length; j++) {
arr[j] = res.get(0).get(j);
}
}
break;
}
}
}
public static void main(String[] args) {
int[] arr = {2, 4, 1, 7, 5, 0};
nextPermutation(arr);
for (int x : arr) {
System.out.print(x + " ");
}
}
}
Python
# Function to generate all possible permutations
def generatePermutations(res, arr, idx):
# Base case: if idx reaches the end of array
if idx == len(arr) - 1:
res.append(arr[:])
return
# Generate all permutations by swapping
for i in range(idx, len(arr)):
arr[idx], arr[i] = arr[i], arr[idx]
# Recur for the next index
generatePermutations(res, arr, idx + 1)
# Backtrack to restore original array
arr[idx], arr[i] = arr[i], arr[idx]
# Function to find the next permutation
def nextPermutation(arr):
res = []
# Generate all permutations
generatePermutations(res, arr, 0)
# Sort all permutations lexicographically
res.sort()
# Find the current permutation index
for i in range(len(res)):
# If current permutation matches input
if res[i] == arr:
# If it's not the last permutation
if i < len(res) - 1:
arr[:] = res[i + 1]
# If it's the last permutation
else:
arr[:] = res[0]
break
if __name__ == "__main__":
arr = [2, 4, 1, 7, 5, 0]
nextPermutation(arr)
for x in arr:
print(x, end=" ")
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to generate all possible permutations
static void generatePermutations(List<List<int>> res,
int[] arr, int idx) {
// Base case: if idx reaches the end of array
if (idx == arr.Length - 1) {
res.Add(new List<int>(arr));
return;
}
// Generate all permutations by swapping
for (int i = idx; i < arr.Length; i++) {
swap(arr, idx, i);
// Recur for the next index
generatePermutations(res, arr, idx + 1);
// Backtrack to restore original array
swap(arr, idx, i);
}
}
static void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
// Function to find the next permutation
static void nextPermutation(int[] arr) {
List<List<int>> res = new List<List<int>>();
// Generate all permutations
generatePermutations(res, arr, 0);
// Sort all permutations lexicographically
res.Sort((a, b) => {
for (int i = 0; i < a.Count; i++) {
if (a[i] != b[i]) return a[i] - b[i];
}
return 0;
});
// Find the current permutation index
for (int i = 0; i < res.Count; i++) {
// If current permutation matches input
bool match = true;
for (int j = 0; j < arr.Length; j++) {
if (arr[j] != res[i][j]) {
match = false;
break;
}
}
if (match) {
// If it's not the last permutation
if (i < res.Count - 1) {
for (int j = 0; j < arr.Length; j++) {
arr[j] = res[i + 1][j];
}
}
// If it's the last permutation
else {
for (int j = 0; j < arr.Length; j++) {
arr[j] = res[0][j];
}
}
break;
}
}
}
static void Main() {
int[] arr = {2, 4, 1, 7, 5, 0};
nextPermutation(arr);
foreach (int x in arr) {
Console.Write(x + " ");
}
}
}
JavaScript
// Function to generate all possible permutations
function generatePermutations(res, arr, idx) {
// Base case: if idx reaches the end of array
if (idx === arr.length - 1) {
res.push([...arr]);
return;
}
// Generate all permutations by swapping
for (let i = idx; i < arr.length; i++) {
[arr[idx], arr[i]] = [arr[i], arr[idx]];
// Recur for the next index
generatePermutations(res, arr, idx + 1);
// Backtrack to restore original array
[arr[idx], arr[i]] = [arr[i], arr[idx]];
}
}
// Function to find the next permutation
function nextPermutation(arr) {
let res = [];
// Generate all permutations
generatePermutations(res, arr, 0);
// Sort all permutations lexicographically
res.sort((a, b) => {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return a[i] - b[i];
}
return 0;
});
// Find the current permutation index
for (let i = 0; i < res.length; i++) {
// If current permutation matches input
let match = true;
for (let j = 0; j < arr.length; j++) {
if (arr[j] !== res[i][j]) {
match = false;
break;
}
}
if (match) {
// If it's not the last permutation
if (i < res.length - 1) {
for (let j = 0; j < arr.length; j++) {
arr[j] = res[i + 1][j];
}
}
// If it's the last permutation
else {
for (let j = 0; j < arr.length; j++) {
arr[j] = res[0][j];
}
}
break;
}
}
}
// Driver Code
let arr = [2, 4, 1, 7, 5, 0];
nextPermutation(arr);
console.log(arr.join(" "));
[Expected Approach] Generating Only Next - O(n) Time and O(1) Space
Let's try some examples to see if we can recognize some patterns.
[1, 2, 3, 4, 5]: next is [1, 2, 3, 5, 4]
Observation: 4 moves and 5 comes in place of it
[1, 2, 3, 5, 4]: next is [1, 2, 4, 3, 5]
Observation: 3 moves, 4 comes in place of it. 3 comes before 5 (mainly 3 and 5 are in sorted order)
[1, 2, 3, 6, 5, 4]: next is [1, 2, 4, 3, 5, 6]
Observation: 3 moves, 4 comes in place of it. [3, 5 and 6 are placed in sorted order]
[3, 2, 1]: next is [1, 2, 3]
Observation: All elements are reverse sorted. Result is whole array sorted.
Observations of Next permutation:
- To get the next permutation we change the number in a position which is as right as possible.
- The first number to be moved is the rightmost number smaller than its next.
- The number to come in-place is the rightmost greater number on right side of the pivot.
Each permutation (except the very first) has an 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:
Step-By-Step Approach:
- 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]).
- If pivot index does not exist, then the given sequence in the array is the largest as possible. So, reverse the complete array. For example, for [3, 2, 1], the output would be [1, 2, 3]
- Otherwise, Iterate the array from the end and find for the successor (rightmost greater element) of pivot in suffix.
- Swap the pivot and successor
- Minimize the suffix part by reversing the array from pivot + 1 till n.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void nextPermutation(vector<int> &arr) {
int n = arr.size();
// Find the pivot index
int pivot = -1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
pivot = i;
break;
}
}
// If pivot point does not exist, reverse the
// whole array
if (pivot == -1) {
reverse(arr.begin(), arr.end());
return;
}
// find the element from the right that
// is greater than pivot
for (int i = n - 1; i > pivot; i--) {
if (arr[i] > arr[pivot]) {
swap(arr[i], arr[pivot]);
break;
}
}
// Reverse the elements from pivot + 1 to the
// end to get the next permutation
reverse(arr.begin() + pivot + 1, arr.end());
}
int main() {
vector<int> arr = { 2, 4, 1, 7, 5, 0 };
nextPermutation(arr);
for (int x : arr)
cout << x << " ";
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void reverse(int arr[], int start, int end) {
while (start < end) {
swap(&arr[start], &arr[end]);
start++;
end--;
}
}
void nextPermutation(int *arr, int n) {
// Find the pivot index
int pivot = -1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
pivot = i;
break;
}
}
// If pivot point does not exist,
// reverse the whole array
if (pivot == -1) {
reverse(arr, 0, n - 1);
return;
}
// Find the element from the right that
// is greater than pivot
for (int i = n - 1; i > pivot; i--) {
if (arr[i] > arr[pivot]) {
swap(&arr[i], &arr[pivot]);
break;
}
}
// Reverse the elements from pivot + 1 to the end
reverse(arr, pivot + 1, n - 1);
}
int main() {
int arr[] = { 2, 4, 1, 7, 5, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
nextPermutation(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
import java.util.Arrays;
class GfG {
static void nextPermutation(int[] arr) {
int n = arr.length;
// Find the pivot index
int pivot = -1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
pivot = i;
break;
}
}
// If pivot point does not exist,
// reverse the whole array
if (pivot == -1) {
reverse(arr, 0, n - 1);
return ;
}
// Find the element from the right
// that is greater than pivot
for (int i = n - 1; i > pivot; i--) {
if (arr[i] > arr[pivot]) {
swap(arr, i, pivot);
break;
}
}
// Reverse the elements from pivot + 1 to the end
reverse(arr, pivot + 1, n - 1);
}
// Helper method to reverse array
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
swap(arr, start++, end--);
}
}
// Helper method to swap two elements
private 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) {
int[] arr = { 2, 4, 1, 7, 5, 0 };
nextPermutation(arr);
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
def nextPermutation(arr):
n = len(arr)
# Find the pivot index
pivot = -1
for i in range(n - 2, -1, -1):
if arr[i] < arr[i + 1]:
pivot = i
break
# If pivot point does not exist,
# reverse the whole array
if pivot == -1:
arr.reverse()
return
# Find the element from the right
# that is greater than pivot
for i in range(n - 1, pivot, -1):
if arr[i] > arr[pivot]:
arr[i], arr[pivot] = arr[pivot], arr[i]
break
# Reverse the elements from pivot + 1 to the end in place
left, right = pivot + 1, n - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
if __name__=="__main__":
arr = [ 2, 4, 1, 7, 5, 0 ]
nextPermutation(arr)
print(" ".join(map(str, arr)))
C#
using System;
class GfG {
static void nextPermutation(int[] arr) {
int n = arr.Length;
// Find the pivot index
int pivot = -1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
pivot = i;
break;
}
}
// If pivot point does not exist, reverse the
// whole array
if (pivot == -1) {
Array.Reverse(arr);
return;
}
// Find the element from the right that
// is greater than pivot
for (int i = n - 1; i > pivot; i--) {
if (arr[i] > arr[pivot]) {
int temp = arr[i];
arr[i] = arr[pivot];
arr[pivot] = temp;
break;
}
}
// Reverse the elements from pivot + 1 to the
// end to get the next permutation
Array.Reverse(arr, pivot + 1, n - pivot - 1);
}
static void Main() {
int[] arr = { 2, 4, 1, 7, 5, 0 };
nextPermutation(arr);
foreach (int x in arr) {
Console.Write(x + " ");
}
}
}
JavaScript
function nextPermutation(arr) {
const n = arr.length;
// Find the pivot index
let pivot = -1;
for (let i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
pivot = i;
break;
}
}
// If pivot point does not exist, reverse the
// whole array
if (pivot === -1) {
arr.reverse();
return;
}
// find the element from the right that
// is greater than pivot
for (let i = n - 1; i > pivot; i--) {
if (arr[i] > arr[pivot]) {
[arr[i], arr[pivot]] = [arr[pivot], arr[i]];
break;
}
}
// Reverse the elements from pivot + 1 to the
// end to get the next permutation in place
let left = pivot + 1;
let right = n - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
// Driver Code
const arr = [2, 4, 1, 7, 5, 0];
nextPermutation(arr);
console.log(arr.join(" "));
[Alternate Approach in C++] Using Inbuilt Function - O(n) Time and O(1) Space
The idea is to use C++'s built-in function next_permutation(), which directly transforms the given array into its next lexicographically greater permutation. If the current arrangement is already the largest possible, this function rearranges the array into the smallest (sorted) permutation.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to find the next permutation
void nextPermutation(vector<int>& arr) {
// Rearranges elements into the next lexicographical order
// If already last permutation, rearranges to the smallest
next_permutation(arr.begin(), arr.end());
}
int main() {
vector<int> arr = {2, 4, 1, 7, 5, 0};
nextPermutation(arr);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
return 0;
}
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read