Next Permutation (original) (raw)

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

Table of Content

[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 #include #include using namespace std;

void generatePermutations(vector<vector> &res, vector &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& 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:

  1. To get the next permutation we change the number in a position which is as right as possible.
  2. The first number to be moved is the rightmost number smaller than its next.
  3. 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:

#include #include #include using namespace std;

void nextPermutation(vector &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 #include #include using namespace std;

// Function to find the next permutation void nextPermutation(vector& 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;

}

`