×

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

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

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.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.