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:
$result = $result / fact($has[$i]);
// return the result
// Driver Code
$str = “MISSISSIPPI”;
// Assuming the string and the character
// are all in uppercase
echo getResult($str, ‘S’).”\n” ;
// This code is contributed by ita_c
- 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
- Count of number of given string in 2D character array
- Maximum length prefix of one string that occurs as subsequence in another
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.