0% found this document useful (0 votes)
17 views

Next - Permutation - Find Next Lexicographically Greater Permutation - Arrays - Tutorial

The document discusses an algorithm to find the next lexicographically greater permutation of a given array of numbers. It explains the intuition and steps of the algorithm which involves finding the breakpoint in the array, swapping the breakpoint element with the next greater element and reversing the portion after the breakpoint.

Uploaded by

Pharoah Gamerz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Next - Permutation - Find Next Lexicographically Greater Permutation - Arrays - Tutorial

The document discusses an algorithm to find the next lexicographically greater permutation of a given array of numbers. It explains the intuition and steps of the algorithm which involves finding the breakpoint in the array, swapping the breakpoint element with the next greater element and reversing the portion after the breakpoint.

Uploaded by

Pharoah Gamerz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

takeUforward

October 24, 2021 • Arrays / Data Structure Search

next_permutation : find next Search

lexicographically greater
permutation
Problem Statement: Given an array Arr[] of integers, rearrange the numbers
of the given array into the lexicographically next greater permutation of
numbers.

If such an arrangement is not possible, it must rearrange to the lowest


possible order (i.e., sorted in ascending order).

Examples

Practice: Solve Problem Solve Problem

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 1/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

Disclaimer: Don’t jump directly to the solution, try it out yourself first.

Solution 1

Solution 2

Using in-built function

C++ provides an in-built function called next_permutation() which directly


returns the lexicographically next greater permutation of the input.

Code

C++ Java Python Javascript

#include<iostream>
#include<vector>
#include<algorithm>
https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 2/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

using namespace std; Latest Video on


takeUforward
int main() {
int arr[] = {1,3,2};
Update on A…
A…
next_permutation(arr,arr+3);//using in-built function

cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2];

return 0;
}

Latest Video on
Output: The next permutation is: 2 1 3
Striver

Solution 3 NEW APART…


APART…

Algorithm / Intuition

The steps are the following:

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 3/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

1. Find the break-point, i: Break-point means the first index i from the
back of the given array where arr[i] becomes smaller than arr[i+1].
For example, if the given array is {2,1,5,4,3,0,0}, the break-point will
be index 1(0-based indexing). Here from the back of the array, index
1 is the first index where arr[1] i.e. 1 is smaller than arr[i+1] i.e. 5.
To find the break-point, using a loop we will traverse the array backward
and store the index i where arr[i] is less than the value at index (i+1) i.e.
arr[i+1].
2. If such a break-point does not exist i.e. if the array is sorted in
decreasing order, the given permutation is the last one in the
sorted order of all possible permutations. So, the next permutation
must be the first i.e. the permutation in increasing order.
So, in this case, we will reverse the whole array and will return it as
our answer.
3. If a break-point exists:

1. Find the smallest number i.e. > arr[i] and in the right half of
index i(i.e. from index i+1 to n-1) and swap it with arr[i].
2. Reverse the entire right half(i.e. from index i+1 to n-1) of
index i. And finally, return the array.
Recent Posts
Kth Missing Positive Number
https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 4/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

Note: For a better understanding of intuition, please watch the video at Capacity to Ship Packages
the bottom of the page. within D Days

Find the Smallest Divisor


Intuition:
Given a Threshold

We build up the intuition of the algorithm through the following Minimum days to make M
observations. bouquets

Koko Eating Bananas


Observations

Observation 1

Let’s try to observe some dictionary-ordered strings like “raj”,


“rax”, and “rbx”. If we carefully observe, we can notice that
these strings contain a common prefix, and the rankings are
done based on the differentiating characters.

Solution
Striver’s SDE 1 “raj”A2Z
Sheet Striver’s
For example, Solution
and 2 a common
DSA Course/Sheet
“rax” has Solution 3 “ra”
Striver’s DSA
prefix i.e.
Playlists CS Subjects Interview Prep Sheets Striver’s CP Sheet
and
the differentiating characters are ‘j’ and ‘x’. Now, as ‘j’ appears
before ‘x’ in the alphabet, “raj” appears before “rax” in the given
order. The same logic is applicable for “rax” and “rbx”(Common
prefix: “r”, differentiating characters: ‘a’ and ‘b’).

The same observation can be done on the permutations of


numbers. For example, if the array is [1, 2, 3], all possible
https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 5/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

permutations in sorted order will look like the following:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

In the above cases, we can also notice that all the


permutations contain an index i(between the first and second
last index) such that its right part is sorted in decreasing order.
Now, if we look at the array in the backward direction, it is
sorted in increasing order up to index i (from n-1 to index i+1).

We can call this index i as the break-point of the array. The left
half of index i (the length of the left half might be 0) in the current
permutation is the same as in the previous permutation. And
the right half of the break-point is always in decreasing order.

The structure of every possible permutation is the following:

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 6/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

After all, we can conclude that the difference between the


next and current permutation always starts at the index i i.e.
the break-point. How to find the break-point in an array:
We can clearly observe that the right half of the break-point
will always be in decreasing order. So, from the backside, the googleads.g.doubleclick.net’s
server IP address could not be
array will be in increasing order up to the break-point index.
found.
Keeping this in mind, we will traverse the array from the
backside and we will break from the first index where arr[i]
becomes smaller than arr[i+1]. The code will look like the
following:

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 7/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

Observation 2

Observation 3

Observation 4

Dry Run

Code

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 8/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

C++ Java Python Javascript

#include <bits/stdc++.h>
using namespace std;

vector<int> nextGreaterPermutation(vector<int> &A) {


int n = A.size(); // size of the array.

// Step 1: Find the break point:


int ind = -1; // break point
for (int i = n - 2; i >= 0; i--) {
if (A[i] < A[i + 1]) {
// index i is the break point
ind = i;
break;
}
}

// If break point does not exist:


if (ind == -1) {
// reverse the whole array:
reverse(A.begin(), A.end());
return A;
}

// Step 2: Find the next greater element

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 9/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

// and swap it with arr[ind]:

for (int i = n - 1; i > ind; i--) {


if (A[i] > A[ind]) {
swap(A[i], A[ind]);
break;
}
}

// Step 3: reverse the right half:


reverse(A.begin() + ind + 1, A.end());

return A;
}

int main()
{
vector<int> A = {2, 1, 5, 4, 3, 0, 0};
vector<int> ans = nextGreaterPermutation(A);

cout << "The next permutation is: [";


for (auto it : ans) {
cout << it << " ";
}
cout << "]n";
return 0;
}

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 10/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

Output: The next permutation is: [2 3 0 0 1 4 5 ]

Complexity Analysis

Video Explanation

Special thanks to Dewanshi Paul and KRITIDIPTA GHOSH for contributing


to this article on takeUforward. If you also wish to share your knowledge
with the takeUforward fam, please check out this article.

« Previous Post Next Post »


Search in a sorted 2D matrix Remove N-th node from the end of a
Linked List

Load Comments

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 11/12
7/9/23, 3:41 PM next_permutation : find next lexicographically greater permutation - Arrays - Tutorial

takeUforward DSA DSA Sheets Contribute


Playlist Striver’s SDE Sheet Write an
The best place to learn data structures, algorithms, most asked
coding interview questions, real interview experiences free of
Array Series Article
cost. Striver’s A2Z DSA

Tree Series Sheet

Follow Us SDE Core Sheet


Graph Series

DP Series Striver’s CP Sheet

Copyright © 2023 takeuforward | All rights reserved

https://takeuforward.org/data-structure/next_permutation-find-next-lexicographically-greater-permutation/ 12/12

You might also like