Generate all permutations of a string that follow given constraints
Last Updated :
11 Jul, 2025
Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring.
Examples:
Input : str = "ABC"
Output : ACB, BAC, BCA, CBA
Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow.
Input : str = "BCD"
Output : BCD, BDC, CDB, CBD, DCB, DBC
A simple solution is to generate all permutations. For every permutation, check if it follows the given constraint.
C++
// Simple C++ program to print all permutations
// of a string that follow given constraint
#include <bits/stdc++.h>
using namespace std;
void permute(string& str, int l, int r)
{
// Check if current permutation is
// valid
if (l == r) {
if (str.find("AB") == string::npos)
cout << str << " ";
return;
}
// Recursively generate all permutation
for (int i = l; i <= r; i++) {
swap(str[l], str[i]);
permute(str, l + 1, r);
swap(str[l], str[i]);
}
}
// Driver Code
int main()
{
string str = "ABC";
permute(str, 0, str.length() - 1);
return 0;
}
Java
// Simple Java program to print all
// permutations of a String that
// follow given constraint
import java.util.*;
class GFG{
static void permute(char[] str, int l, int r)
{
// Check if current permutation is
// valid
if (l == r)
{
if (!String.valueOf(str).contains("AB"))
System.out.print(String.valueOf(str) + " ");
return;
}
// Recursively generate all permutation
for(int i = l; i <= r; i++)
{
char tmp = str[l];
str[l] = str[i];
str[i] = tmp;
permute(str, l + 1, r);
tmp = str[l];
str[l] = str[i];
str[i] = tmp;
}
}
// Driver Code
public static void main(String[] args)
{
String str = "ABC";
permute(str.toCharArray(), 0,
str.length() - 1);
}
}
// This code is contributed by Amit Katiyar
Python
# Simple Python program to print all permutations
# of a string that follow given constraint
def permute(str, l, r):
# Check if current permutation is
# valid
if (l == r):
if "AB" not in ''.join(str):
print(''.join(str), end=" ")
return
# Recursively generate all permutation
for i in range(l, r + 1):
str[l], str[i] = str[i], str[l]
permute(str, l + 1, r)
str[l], str[i] = str[i], str[l]
# Driver Code
str = "ABC"
permute(list(str), 0, len(str) - 1)
# This code is contributed by SHUBHAMSINGH10
C#
// Simple C# program to print all permutations
// of a string that follow given constraint
using System;
using System.Text;
class GFG {
static void permute(StringBuilder str, int l, int r)
{
// Check if current permutation is
// valid
if (l == r) {
if (str.ToString().IndexOf("AB") == -1) {
Console.Write(str.ToString() + " ");
}
return;
}
// Recursively generate all permutation
for (int i = l; i <= r; i++) {
char tmp = str[l];
str[l] = str[i];
str[i] = tmp;
permute(str, l + 1, r);
tmp = str[l];
str[l] = str[i];
str[i] = tmp;
}
}
// Driver code
static void Main(string[] arg)
{
string str = "ABC";
StringBuilder s = new StringBuilder(str);
permute(s, 0, str.Length - 1);
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// JavaScript code to implement the above approach
function permute(str, l, r)
{
// Check if current permutation is
// valid
if (l == r) {
if (str.indexOf("AB") == -1)
document.write(str," ");
return;
}
// Recursively generate all permutation
for (let i = l; i <= r; i++) {
let a = str.split("");
let temp = a[l];
a[l] = a[i];
a[i] = temp;
permute(a.join(""), l + 1, r);
temp = a[l];
a[l] = a[i];
a[i] = temp;
}
}
// Driver Code
let str = "ABC";
permute(str, 0, str.length - 1);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(n! X n) where n! is the number of permutations generated and O(n) times to print a permutation.
Auxiliary Space: O(n! X n )
The above solution first generates all permutations, then for every permutation, it checks if it follows given constraint or not.

An efficient solution is to use Backtracking. We cut down the recursion tree whenever we see that substring "AB" is formed. How do we do this? we add a isSafe() function. Before doing a swap, we check if previous character is 'A' and current character is 'B'.
Below is the implementation of the above code:
C++
// Backtracking based CPP program to print all
// permutations of a string that follow given
// constraint
#include <bits/stdc++.h>
using namespace std;
bool isSafe(string& str, int l, int i, int r)
{
// If previous character was 'A' and character
// is 'B', then do not proceed and cut down
// the recursion tree.
if (l != 0 && str[l - 1] == 'A' && str[i] == 'B')
return false;
// This condition is explicitly required for
// cases when last two characters are "BA". We
// do not want them to swapped and become "AB"
if (r == l + 1 && str[i] == 'A' && str[l] == 'B'
|| r == l + 1 && l == i && str[r] == 'B'
&& str[l] == 'A')
return false;
return true;
}
void permute(string& str, int l, int r)
{
// We reach here only when permutation
// is valid
if (l == r) {
cout << str << " ";
return;
}
// Fix all characters one by one
for (int i = l; i <= r; i++) {
// Fix str[i] only if it is a
// valid move.
if (isSafe(str, l, i, r)) {
swap(str[l], str[i]);
permute(str, l + 1, r);
swap(str[l], str[i]);
}
}
}
// Driver Code
int main()
{
string str = "ABC";
// Function call
permute(str, 0, str.length() - 1);
return 0;
}
Java
// Backtracking based JAVA program
// to print all permutations of a
// string that follow given constraint
public class GFG
{
public boolean isSafe(String str,
int l,
int i,
int r)
{
// If previous character was 'A'
// and character is 'B', then
// do not proceed and cut down the
// recursion tree.
if (l != 0 && str.charAt(l - 1) == 'A'
&& str.charAt(i) == 'B')
return false;
// This condition is explicitly required
// for cases when last two characters
// are "BA". We do not want them to
// swapped and become "AB"
if (r == l + 1 && str.charAt(i) == 'A'
&& str.charAt(l) == 'B'
|| r == l + 1 && l == i
&& str.charAt(r) == 'B'
&& str.charAt(l) == 'A')
return false;
return true;
}
/**
* permutation function
* @param str string to calculate
permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str,
int l, int r)
{
// We reach here only when permutation
// is valid
if (l == r)
System.out.print(str + " ");
else
{
// Fix all characters one by one
for (int i = l; i <= r; i++)
{
// Fix str[i] only if it is a
// valid move.
if (isSafe(str, l, i, r))
{
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
// Driver Code
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
GFG permutation = new GFG();
// Function call
permutation.permute(str, 0, n - 1);
}
}
Python
# Backtracking based Python3 program to print all
# permutations of a string that follow given
# constraint
def isSafe(str, l, i, r):
# If previous character was 'A' and character
# is 'B', then do not proceed and cut down
# the recursion tree.
if (l != 0 and str[l - 1] == 'A' and str[i] == 'B'):
return False
# This condition is explicitly required for
# cases when last two characters are "BA". We
# do not want them to swapped and become "AB"
if (r == l + 1 and str[i] == 'A' and str[l] == 'B'
or r == l + 1 and l == i and str[r] == 'B'
and str[l] == 'A'):
return False
return True
def permute(str, l, r):
# We reach here only when permutation
# is valid
if (l == r):
print(*str, sep="", end=" ")
return
# Fix all characters one by one
for i in range(l, r + 1):
# Fix str[i] only if it is a
# valid move.
if (isSafe(str, l, i, r)):
str[l], str[i] = str[i], str[l]
permute(str, l + 1, r)
str[l], str[i] = str[i], str[l]
# Driver Code
str = "ABC"
# Function call
permute(list(str), 0, len(str) - 1)
# This code is contributed by SHUBHAMSINGH10
C#
// Backtracking based C# program to print all
// permutations of a string that follow given
// constraint
using System;
public class GFG
{
// Backtracking based C# program
// to print all permutations of a
// string that follow given constraint
using System;
using System.Text;
class GFG {
static bool isSafe(StringBuilder str,
int l, int i,
int r)
{
// If previous character was 'A'
// and character is 'B', then do not
// proceed and cut down the recursion tree.
if (l != 0 && str[l - 1] == 'A'
&& str[i] == 'B')
return false;
// This condition is explicitly
// required for cases when last two
// characters are "BA". We do not want
// them to swapped and become "AB"
if (r == l + 1 && str[i] == 'A'
&& str[l] == 'B' || r == l + 1
&& l == i && str[r] == 'B'
&& str[l] == 'A')
return false;
return true;
}
static void permute(StringBuilder str,
int l, int r)
{
// We reach here only when permutation
// is valid
if (l == r)
{
Console.Write(str + " ");
return;
}
// Fix all characters one by one
for (int i = l; i <= r; i++)
{
// Fix str[i] only if it is a
// valid move.
if (isSafe(str, l, i, r))
{
char temp = str[l];
str[l] = str[i];
str[i] = temp;
permute(str, l + 1, r);
temp = str[l];
str[l] = str[i];
str[i] = temp;
}
}
}
// Driver code
static void Main()
{
string str = "ABC";
StringBuilder s = new StringBuilder(str);
// Function call
permute(s, 0, str.Length - 1);
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
const GFG = {
isSafe(str, l, i, r) {
// If previous character was 'A'
// and character is 'B', then
// do not proceed and cut down the
// recursion tree.
if (l !== 0 && str[l - 1] === 'A' && str[i] === 'B') return false;
// This condition is explicitly required
// for cases when last two characters
// are "BA". We do not want them to
// swapped and become "AB"
if ((r === l + 1 && str[i] === 'A' && str[l] === 'B')
|| (r === l + 1 && l === i && str[r] === 'B' && str[l] === 'A')) {
return false;
}
return true;
},
permute(str, l, r) {
// We reach here only when permutation
// is valid
if (l === r) console.log(`${str} `);
else {
// Fix all characters one by one
for (let i = l; i <= r; i++) {
// Fix str[i] only if it is a
// valid move.
if (this.isSafe(str, l, i, r)) {
str = this.swap(str, l, i);
this.permute(str, l + 1, r);
str = this.swap(str, l, i);
}
}
}
},
swap(a, i, j) {
let temp;
const charArray = a.split('');
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return charArray.join('');
},
};
// Driver Code
const str = 'ABC';
const n = str.length;
// Function call
GFG.permute(str, 0, n - 1);
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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