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
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem