Print all lexicographical greater permutations of a given string
Last Updated :
07 Nov, 2023
Given a string S, print those permutations of string S which are lexicographically greater than S. If there is no such permutation of string, print -1.
Examples:
Input : BCA
Output : CAB, CBA
Explanation: Here, S = "BCA", and there are 2 strings "CAB, CBA" which are lexicographically greater than S.
Input : CBA
Output : -1 There is no string which is lexicographically greater than S, so the output is -1.
Approach: To solve the problem mentioned above we will use STL. Use next_permuation() and prev_permutation() functions to check and the lexicographically greater strings. If the string is greater then print it otherwise print -1. Below is the implementation of above approach:
CPP
// C++ program to print the lexicographically
// greater strings then the given string
#include <bits/stdc++.h>
using namespace std;
// Function to print the lexicographically
// greater strings then the given string
void print_lexiStrings(string S)
{
// Condition to check if there is no
// string which is lexicographically
// greater than string S
if (!next_permutation(S.begin(), S.end()))
cout<<-1<<endl;
// Move to the previous permutation
prev_permutation(S.begin(), S.end());
// Iterate over all the
// lexicographically greater strings
while (next_permutation(S.begin(), S.end())) {
cout<<S<<endl;
}
}
// Driver Code
int main()
{
string S = "ABC";
print_lexiStrings(S);
}
Java
import java.util.*;
public class Main {
// Function to print the lexicographically
// greater strings then the given string
public static void printLexiStrings(String S) {
// Convert the string to a character array
char[] charArray = S.toCharArray();
// Condition to check if there is no
// string which is lexicographically
// greater than string S
boolean hasNext = true;
for (int i = charArray.length - 2; i >= 0; i--) {
if (charArray[i] < charArray[i + 1]) {
int j = charArray.length - 1;
while (charArray[j] <= charArray[i]) {
j--;
}
swap(charArray, i, j);
reverse(charArray, i + 1, charArray.length - 1);
hasNext = false;
break;
}
}
if (hasNext) {
System.out.println(-1);
}
// Iterate over all the
// lexicographically greater strings
while (!hasNext) {
System.out.println(new String(charArray));
hasNext = true;
for (int i = charArray.length - 2; i >= 0; i--) {
if (charArray[i] < charArray[i + 1]) {
int j = charArray.length - 1;
while (charArray[j] <= charArray[i]) {
j--;
}
swap(charArray, i, j);
reverse(charArray, i + 1, charArray.length - 1);
hasNext = false;
break;
}
}
}
}
// Utility function to swap two characters in an array
private static void swap(char[] charArray, int i, int j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// Utility function to reverse the subarray from index i to j
private static void reverse(char[] charArray, int i, int j) {
while (i < j) {
swap(charArray, i, j);
i++;
j--;
}
}
// Driver Code
public static void main(String[] args) {
String S = "ABC";
printLexiStrings(S);
}
}
Python3
import itertools
# Define a function that finds lexicographically greater permutations of the given string
def print_lexiStrings(S):
# Convert the string into a list of characters
S_list = list(S)
# Use the itertools.permutations function to generate all permutations of the list of characters
# and keep only the ones that are lexicographically greater than the original string
lex_greater_permutations = [''.join(perm) for perm in itertools.permutations(S_list) if perm > tuple(S_list)]
# If there are any permutations that are lexicographically greater than the original string, print them
if lex_greater_permutations:
for perm in lex_greater_permutations:
print(perm)
# If there are no permutations that are lexicographically greater than the original string, print -1
else:
print(-1)
# Driver Code
if __name__ == "__main__":
# Test the function with an example string
S = "ABC"
print_lexiStrings(S)
C#
using System;
using System.Linq;
class Program
{
static void print_lexiStrings(string S)
{
// Convert the string to a character array
char[] arr = S.ToCharArray();
// Condition to check if there is no
// string which is lexicographically
// greater than string S
if (!next_permutation(arr))
Console.WriteLine("-1");
// Move to the previous permutation
prev_permutation(arr);
// Iterate over all the
// lexicographically greater strings
while (next_permutation(arr))
{
Console.WriteLine(new string(arr));
}
}
static bool next_permutation(char[] arr)
{
int i = arr.Length - 2;
while (i >= 0 && arr[i] >= arr[i + 1])
{
i--;
}
if (i < 0)
{
return false;
}
int j = arr.Length - 1;
while (j > i && arr[j] <= arr[i])
{
j--;
}
swap(arr, i, j);
reverse(arr, i + 1, arr.Length - 1);
return true;
}
static void prev_permutation(char[] arr)
{
int i = arr.Length - 2;
while (i >= 0 && arr[i] <= arr[i + 1])
{
i--;
}
if (i < 0)
{
return;
}
int j = arr.Length - 1;
while (j > i && arr[j] >= arr[i])
{
j--;
}
swap(arr, i, j);
reverse(arr, i + 1, arr.Length - 1);
}
static void swap(char[] arr, int i, int j)
{
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void reverse(char[] arr, int i, int j)
{
while (i < j)
{
swap(arr, i, j);
i++;
j--;
}
}
static void Main(string[] args)
{
string S = "ABC";
print_lexiStrings(S);
}
}
JavaScript
function printLexiStrings(S) {
// Convert the string to a character array
let charArray = S.split('');
// Condition to check if there is no
// string which is lexicographically
// greater than string S
let hasNext = true;
for (let i = charArray.length - 2; i >= 0; i--) {
if (charArray[i] < charArray[i + 1]) {
let j = charArray.length - 1;
while (charArray[j] <= charArray[i]) {
j--;
}
swap(charArray, i, j);
reverse(charArray, i + 1, charArray.length - 1);
hasNext = false;
break;
}
}
if (hasNext) {
console.log(-1);
}
// Iterate over all the
// lexicographically greater strings
while (!hasNext) {
console.log(charArray.join(''));
hasNext = true;
for (let i = charArray.length - 2; i >= 0; i--) {
if (charArray[i] < charArray[i + 1]) {
let j = charArray.length - 1;
while (charArray[j] <= charArray[i]) {
j--;
}
swap(charArray, i, j);
reverse(charArray, i + 1, charArray.length - 1);
hasNext = false;
break;
}
}
}
}
// Utility function to swap two characters in an array
function swap(charArray, i, j) {
let temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
// Utility function to reverse the subarray from index i to j
function reverse(charArray, i, j) {
while (i < j) {
swap(charArray, i, j);
i++;
j--;
}
}
// Driver Code
let S = "ABC";
printLexiStrings(S);
OutputACB
BAC
BCA
CAB
CBA
Time Complexity : O(N*N!), As next_permutation takes O(N!) for finding all the permutations and in order to print the string it will take O(N) time complexity, where N is the length of the string.
Auxiliary Space : O(1)
New Approach:- Here, another approach to solve This program prints all the lexicographically greater permutations of a given string using the following algorithm:
1. Initialize a flag variable "found" to false.
2. Start a do-while loop that runs until a greater permutation is not found.
3. Find the largest index k such that S[k] < S[k+1] by iterating over the string from left to right.
4. If no such index exists, break out of the loop because the given permutation is already the largest possible.
5. Find the largest index l such that S[k] < S[l] by iterating over the string from k+1 to the end.
6. Swap S[k] and S[l].
7. Reverse the sequence from S[k+1] up to the end of the string.
8. Print the lexicographically greater string.
9. Set the flag to true.
10. Repeat the above steps until there are no more greater permutations left.
11. If no greater permutation was found, print -1.
In this way, the program prints all the lexicographically greater permutations of the given string.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to print all the lexicographically greater strings
void print_lexiStrings(string S)
{
int n = S.size();
// Flag variable to keep track of whether a greater permutation was found
bool found = false;
do {
// Find the largest index k such that S[k] < S[k+1]
int k = -1;
for (int i = 0; i < n - 1; i++) {
if (S[i] < S[i+1])
k = i;
}
// If no such index exists, the permutation is already the largest possible
if (k == -1)
break;
// Find the largest index l such that S[k] < S[l]
int l = -1;
for (int i = k+1; i < n; i++) {
if (S[k] < S[i])
l = i;
}
// Swap S[k] and S[l]
swap(S[k], S[l]);
// Reverse the sequence from S[k+1] up to the end of the string
reverse(S.begin() + k + 1, S.end());
// Print the lexicographically greater string
cout << S << "\n";
// Set the flag to true
found = true;
} while (found);
// If no greater permutation was found, print -1
if (!found)
cout << "-1\n";
}
// Driver Code
int main()
{
string S = "ABC";
print_lexiStrings(S);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to print all the lexicographically greater
// strings
static void printLexiStrings(String s)
{
char[] S = s.toCharArray();
int n = S.length;
// Flag variable to keep track of whether a greater
// permutation was found
boolean found = false;
do {
// Find the largest index k such that S[k] <
// S[k+1]
int k = -1;
for (int i = 0; i < n - 1; i++) {
if (S[i] < S[i + 1])
k = i;
}
// If no such index exists, the permutation is
// already the largest possible
if (k == -1)
break;
// Find the largest index l such that S[k] <
// S[l]
int l = -1;
for (int i = k + 1; i < n; i++) {
if (S[k] < S[i])
l = i;
}
// Swap S[k] and S[l]
char temp = S[k];
S[k] = S[l];
S[l] = temp;
// Reverse the sequence from S[k+1] up to the
// end of the array
for (int i = k + 1, j = n - 1; i < j;
i++, j--) {
temp = S[i];
S[i] = S[j];
S[j] = temp;
}
// Print the lexicographically greater string
System.out.println(String.valueOf(S));
// Set the flag to true
found = true;
} while (found);
// If no greater permutation was found, print -1
if (!found)
System.out.println("-1");
}
// Driver Code
public static void main(String[] args)
{
String S = "ABC";
printLexiStrings(S);
}
}
Python3
# Pytho program for above approach
def print_lexi_strings(S):
n = len(S)
found = False
while True:
# Find the largest index k such that S[k] < S[k+1]
k = -1
for i in range(n - 1):
if S[i] < S[i + 1]:
k = i
# If no such index exists, break the loop
if k == -1:
break
# Find the largest index l such that S[k] < S[l]
l = -1
for i in range(k + 1, n):
if S[k] < S[i]:
l = i
# Swap S[k] and S[l]
S_list = list(S)
S_list[k], S_list[l] = S_list[l], S_list[k]
S = ''.join(S_list)
# Reverse the sequence from S[k+1] up to the end of the string
S = S[:k + 1] + S[k + 1:][::-1]
# Print the lexicographically greater string
print(S)
# Set the flag to True
found = True
# If no greater permutation was found, print -1
if not found:
print("-1")
# Driver Code
if __name__ == "__main__":
S = "ABC"
print_lexi_strings(S)
C#
using System;
class Program
{
// Function to print all the lexicographically greater strings
static void PrintLexiStrings(string s)
{
int n = s.Length;
// Flag variable to keep track of whether a greater permutation was found
bool found = false;
do
{
// Find the largest index k such that S[k] < S[k+1]
int k = -1;
for (int i = 0; i < n - 1; i++)
{
if (s[i] < s[i + 1])
k = i;
}
// If no such index exists, the permutation is already the largest possible
if (k == -1)
break;
// Find the largest index l such that S[k] < S[l]
int l = -1;
for (int i = k + 1; i < n; i++)
{
if (s[k] < s[i])
l = i;
}
// Convert the string to a char array for swapping
char[] chars = s.ToCharArray();
// Swap S[k] and S[l]
char temp = chars[k];
chars[k] = chars[l];
chars[l] = temp;
s = new string(chars);
// Reverse the sequence from S[k+1] up to the end of the string
char[] subArray = s.Substring(k + 1).ToCharArray();
Array.Reverse(subArray);
s = s.Substring(0, k + 1) + new string(subArray);
// Print the lexicographically greater string
Console.WriteLine(s);
// Set the flag to true
found = true;
}
while (found);
// If no greater permutation was found, print -1
if (!found)
Console.WriteLine("-1");
}
// Driver Code
static void Main()
{
string S = "ABC";
PrintLexiStrings(S);
}
}
// This code is contributed by Dwaipayan Bandyopadhyay
JavaScript
function printLexiStrings(S) {
const n = S.length;
let found = false;
S = S.split('');
do {
// Find the largest index k such that S[k] < S[k+1]
let k = -1;
for (let i = 0; i < n - 1; i++) {
if (S[i] < S[i + 1]) {
k = i;
}
}
// If no such index exists, the permutation is already the largest possible
if (k === -1) {
break;
}
// Find the largest index l such that S[k] < S[l]
let l = -1;
for (let i = k + 1; i < n; i++) {
if (S[k] < S[i]) {
l = i;
}
}
// Swap S[k] and S[l]
[S[k], S[l]] = [S[l], S[k]];
// Reverse the sequence from S[k+1] up to the end of the array
let i = k + 1;
let j = n - 1;
while (i < j) {
[S[i], S[j]] = [S[j], S[i]];
i++;
j--;
}
// Print the lexicographically greater string
console.log(S.join(''));
// Set the flag to true
found = true;
} while (found);
// If no greater permutation was found, print -1
if (!found) {
console.log("-1");
}
}
const S = "ABC";
printLexiStrings(S);
Output:-
ACB
BAC
BCA
CAB
CBA
Time complexity:- Time complexity of the given implementation is O(n!), where n is the length of the string. This is because there are n! possible permutations of the string, and we are checking all of them.
Auxiliary Space:- The auxiliary space used by the program is O(n), where n is the length of the string. This is because we are only storing the input string and a few integer variables. Therefore, the space complexity is constant with respect to the input size.
Similar Reads
Print all permutations in sorted (lexicographic) order
Given a string s, print all unique permutations of the string in lexicographically sorted order.Examples:Input: "ABC"Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]Explanation: All characters are distinct, so there are 3! = 6 unique permutations, printed in sorted order.Input: "AAA"Output: ["AAA"
15+ min read
Lexicographically Next Permutation of given String
All the permutations of a word when arranged in a dictionary, the order of words so obtained is called lexicographical order. in Simple words, it is the one that has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order. lexicographically is noth
8 min read
Print all permutations of a string in Java
Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words âbatâ and âtabâ represents two distinct permutation (or arrangements) of a similar three lett
3 min read
Find n-th lexicographically permutation of a string | Set 2
Given a string of length m containing lowercase alphabets only. We need to find the n-th permutation of string lexicographic ally. Examples: Input: str[] = "abc", n = 3 Output: Result = "bac" All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input: str[] = "aba", n = 2 Output: R
11 min read
Print all Unique permutations of a given string.
Given a string that may contain duplicates, the task is find all unique permutations of given string in any order.Examples: Input: "ABC"Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]Explanation: Given string ABC has 6 unique permutations as "ABC", "ACB", "BAC", "BCA", "CAB" and "CBA".Input: "AAA
12 min read
Lexicographically n-th permutation of a string
Given a string of length m containing lowercase alphabets only. You have to find the n-th permutation of string lexicographically. Examples: Input : str[] = "abc", n = 3 Output : Result = "bac" Explanation : All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input : str[] = "aba"
6 min read
Print all the combinations of a string in lexicographical order
Given a string str, print of all the combinations of a string in lexicographical order.Examples: Input: str = "ABC" Output: A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA Input: ED Output: D DE E ED Approach: Count the occurrences of all the characters in the string using a map, then using recursio
9 min read
Lexicographically smallest permutation of [1, N] based on given Binary string
Given a binary string S of size (N - 1), the task is to find the lexicographically smallest permutation P of the first N natural numbers such that for every index i, if S[i] equals '0' then P[i + 1] must be greater than P[i] and if S[i] equals '1' then P[i + 1] must be less than P[i]. Examples: Inpu
6 min read
All permutations of a string using iteration
A permutation, also called an âarrangement numberâ or âorderâ, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
4 min read
Check if any permutation of a given string is lexicographically larger than the other given string
Given two strings str1 and str2 of same length N, the task is to check if there exists any permutation possible in any of the given strings, such that every character of one string is greater or equal to every character of the other string, at corresponding indices. Return true if permutation exists
10 min read