Given a string ‘s’ and a character ‘c’, the task is to find the number of permutations of the string in which all the occurrences of the character ‘c’ will be together (one after another).
Input: Str = “AKA” ch = ‘A’
All the unique permutations of AKA are : AKA, AAK and KAA
‘A’ comes consecutively only twice. Hence, the answer is 2
Input: str= “MISSISSIPPI” ch = ‘S’
- Generate all the permutations of the given string.
- For each permutation check whether all occurrences of the character appear together.
- Count of the permutations from the previous step is the answer.
Efficient Approach: Let the length of the string be ‘l’ and frequency of the character in the string be ‘n’.
- Store the frequency of every character of the string.
- If the character is not present in the string then the output will be ‘0’.
- Consider all the occurrences of the character as a combined single character.
- So, ‘l’ will become ‘l – occ + 1’ where ‘occ’ is the total occurrence of the given character and ‘l’ is the new length of the string.
- Return ( (Factorial of l) / (Product of the factorials of the no. of occurrences of each character except the given character) )
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Map every character of one string to another such that all occurrences are mapped to the same character
- Remove all occurrences of a character in a string
- Count occurrences of a character in a repeated string
- Queries to print the character that occurs the maximum number of times in a given range
- Print the string by ignoring alternate occurrences of any character
- Find the number of occurrences of a character upto preceding position
- Number of times the given string occurs in the array in the range [l, r]
- Longest subsequence where each character occurs at least k times
- Lexicographically largest subsequence such that every character occurs at least k times
- Number of unique permutations starting with 1 of a Binary String
- Check if all occurrences of a character appear together
- Minimize ASCII values sum after removing all occurrences of one character
- Maximum number of characters between any two same character in a string
- Number of ways to convert a character X to a string Y
- Count of number of given string in 2D character array