Print all lexicographical greater permutations of a given string
Last Updated :
15 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem