×

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example, will be followed by "BAC." The lexicographically next permutation is not present in some cases, such as "BBB" or "DCBA."

Lexicographical Order

When all the permutations of a word are sorted in a dictionary, the resulting order of words is known as lexicographical order. Simply said, it is the one with all of its elements sorted ascending, whereas the largest has all of its elements sorted descending. It is nothing more than the greatest permutation of it lexicographically.

a b c d e f g h I j k l m n o p q r s t u v w x y z as a guide.

The next lexicographic permutation of "jtp" is "pjt."

Keep in Mind: In some circumstances, such as "aaa" and "edcba," the next lexicographically bigger word may not exist.

In C++, there is a function that relieves us from writing a huge amount of code. It's in the #include<algorithm> file. next_permutation(a.begin(), a.end()) is the function.

If the function can rearrange the item into a lexicographically greater permutation, it returns 'true.' If not, the method returns 'false.'

Example:

C++ Program

// A CPP code that displays the next lexicographically greater permutation of a word.
#include <algorithm>
#include <iostream>
using namespace std;


int main ()
{
	string strng = { "jtp" };
	bool value
		= next_permutation ( strng.begin (),
						strng.end () );
	if ( value == false )
		cout << "No Word Possible"
			<< endl;
	else
		cout << strng << endl;
	return 0;
}

Output:

pjt

The identical code can also be written without the use of STL. The code for this is shown below.

The following facts Illustrate the Concept:

  1. The next permutation does not exist in a specific order arranged in descending order. The following permutation, for example, does not exist for "edcba."
  2. These steps can be used for a specific order that is not arranged in descending order, such as "abedc."
    • From the right, find the first item that does not follow the ascending order. In "abedc," for example, the character 'b' doesn't at all pursue the ascending order.
    • Replace the detected character with the nearest greater (or smallest greater) element on its right side. In the case of "abedc," the nearest bigger element is 'c'. After exchanging the letters 'b' and 'c,' the string becomes "acedb."
    • Following swapping, turn the string after the character detected in step a. We get "acbde" after reversing the substring "edb" of "acedb." This is the desired next permutation.
      Steps b) and c) performance enhancements
    • We utilise binary search to discover the nearest bigger element because the sequence is arranged in decreasing order.
    • Because the sequence is arranged in decreasing order, one utilise binary search to locate the nearest greater element.

C++ Program

// CPP code that displays the next lexicographically greater permutation of a word.
#include <iostream>
using namespace std;


void swap ( char* x, char* y )
{
	if ( *x == *y )
		return;
	*x ^= *y;
	*y ^= *x;
	*x ^= *y;
}
void revs ( string& strng, int a, int b )
{
	while ( a < b )
		swap ( &strng [a++], &strng [b--] );
}
int binarysearch ( string& strng, int a, int b, int key )
{
	int index = -1;
	while ( a <= b ) {
		int mid = a + ( b - a ) / 2;
		if ( strng [mid] <= key )
			b = mid - 1;
		else {
			a = mid + 1;
			if ( index == -1 || strng [index] >= strng [mid] )
				index = mid;
		}
	}
	return index;
}


bool nextpermutation ( string& strng )
{
	int len = strng.length(), i = len - 2;
	while ( i >= 0 && strng [i] >= strng [i + 1] )
		--i;
	if ( i < 0 )
		return false;
	else {
		int index = binarysearch ( strng, i + 1, len - 1, strng[i] );
		swap ( &strng [i], &strng [index] );
		revs ( strng, i + 1, len - 1 );
		return true;
	}
}
int main ()
{
	string strng = { "jtp" };
	bool value = nextpermutation (strng);
	if ( value == false )
		cout << "No Word Possible" << endl;
	else
		cout << strng << endl;
	return 0;
}

Output:

pjt

Time Complexity:

  • The initial step of next_permutation tends to take O(n) time in the worst-case scenario.
  • The binary search tends to take O(log n) time to complete.
  • The reverse tends to take O(n) time.

O(n) is the overall temporal complexity, here n is the string's length.

Space Complexity:

As no extra space is used, Space complexity will be O(1).


Related Topics

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.