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.
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.
ACB BAC BCA CBA
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’.
ACB BAC BCA CBA
- Iterative program to generate distinct Permutations of a String
- Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
- Generate all cyclic permutations of a number
- Generate permutations with only adjacent swaps allowed
- Check if it is possible to convert one string into another with given constraints
- Construct a binary string following the given constraints
- Permutations of a given string using STL
- Distinct permutations of the string | Set 2
- All permutations of a string using iteration
- Time complexity of all permutations of a string
- Print all palindrome permutations of a string
- Print all permutations of a string in Java
- Permutations of string such that no two vowels are adjacent
- Print all distinct permutations of a given string with duplicates
- Count of cyclic permutations having XOR with other binary string as 0
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SHUBHAMSINGH10