Number of permutations of a string in which all the occurrences of a given character occurs together
Last Updated :
20 Apr, 2023
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).
Examples :
Input: Str = "AKA" ch = 'A'
Output: 2
Explanation: 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'
Output: 840
Naive Approach:
- Generate all the permutations of the given string.
- For each permutation check whether all occurrences of the character appear together.
- The count of the permutations from the previous step is the answer.
Efficient Approach: Let the length of the string be 'l' and the 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:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return factorial
// of the number passed as argument
long long int fact(int n)
{
long long result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
// Function to get the total permutations
// which satisfy the given condition
int getResult(string str, char ch)
{
// Create has to store count
// of each character
int has[26] = { 0 };
// Store character occurrences
for (int i = 0; i < str.length(); i++)
has[str[i] - 'A']++;
// Count number of times
// Particular character comes
int particular = has[ch - 'A'];
// If particular character isn't
// present in the string then return 0
if (particular == 0)
return 0;
// Remove count of particular character
has[ch - 'A'] = 0;
// Total length
// of the string
int total = str.length();
// Assume all occurrences of
// particular character as a
// single character.
total = total - particular + 1;
// Compute factorial of the length
long long int result = fact(total);
// Divide by the factorials of
// the no. of occurrences of all
// the characters.
for (int i = 0; i < 26; i++) {
if (has[i] > 1) {
result = result / fact(has[i]);
}
}
// return the result
return result;
}
// Driver Code
int main()
{
string str = "MISSISSIPPI";
// Assuming the string and the character
// are all in uppercase
cout << getResult(str, 'S') << endl;
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class solution
{
// Function to return factorial
// of the number passed as argument
static int fact(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
// Function to get the total permutations
// which satisfy the given condition
static int getResult(String str, char ch)
{
// Create has to store count
// of each character
int has[] = new int[26];
for(int i=0;i<26;i++)
has[i]=0;
// Store character occurrences
for (int i = 0; i < str.length(); i++)
has[str.charAt(i) - 'A']++;
// Count number of times
// Particular character comes
int particular = has[ch - 'A'];
// If particular character isn't
// present in the string then return 0
if (particular == 0)
return 0;
// Remove count of particular character
has[ch - 'A'] = 0;
// Total length
// of the string
int total = str.length();
// Assume all occurrences of
// particular character as a
// single character.
total = total - particular + 1;
// Compute factorial of the length
int result = fact(total);
// Divide by the factorials of
// the no. of occurrences of all
// the characters.
for (int i = 0; i < 26; i++) {
if (has[i] > 1) {
result = result / fact(has[i]);
}
}
// return the result
return result;
}
// Driver Code
public static void main(String args[])
{
String str = "MISSISSIPPI";
// Assuming the string and the character
// are all in uppercase
System.out.println( getResult(str, 'S') );
}
}
//contributed by Arnab Kundu
Python 3
# Python3 implementation of
# the approach
# Function to return factorial
# of the number passed as argument
def fact(n) :
result = 1
for i in range(1, n + 1) :
result *= i
return result
# Function to get the total permutations
# which satisfy the given condition
def getResult(string, ch):
# Create has to store count
# of each character
has = [0] * 26
# Store character occurrences
for i in range(len(string)) :
has[ord(string[i]) - ord('A')] += 1
# Count number of times
# Particular character comes
particular = has[ord(ch) - ord('A')]
# If particular character isn't
# present in the string then return 0
if particular == 0 :
return 0
# Remove count of particular character
has[ord(ch) - ord('A')] = 0
# Total length
# of the string
total = len(string)
# Assume all occurrences of
# particular character as a
# single character.
total = total - particular + 1
# Compute factorial of the length
result = fact(total)
# Divide by the factorials of
# the no. of occurrences of all
# the characters.
for i in range(26) :
if has[i] > 1 :
result /= fact(has[i])
# return the result
return result
# Driver code
if __name__ == "__main__" :
string = "MISSISSIPPI"
# Assuming the string and the character
# are all in uppercase
print(getResult(string,'S'))
# This code is contributed
# by ANKITRAI1
C#
// C# implementation of above approach
using System;
class GFG
{
// Function to return factorial
// of the number passed as argument
static int fact(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
// Function to get the total permutations
// which satisfy the given condition
static int getResult(string str, char ch)
{
// Create has to store count
// of each character
int []has = new int[26];
for(int i = 0; i < 26; i++)
has[i] = 0;
// Store character occurrences
for (int i = 0; i < str.Length; i++)
has[str[i] - 'A']++;
// Count number of times
// Particular character comes
int particular = has[ch - 'A'];
// If particular character
// isn't present in the string
// then return 0
if (particular == 0)
return 0;
// Remove count of particular character
has[ch - 'A'] = 0;
// Total length of the string
int total = str.Length;
// Assume all occurrences of
// particular character as a
// single character.
total = total - particular + 1;
// Compute factorial of the length
int result = fact(total);
// Divide by the factorials of
// the no. of occurrences of all
// the characters.
for (int i = 0; i < 26; i++)
{
if (has[i] > 1)
{
result = result / fact(has[i]);
}
}
// return the result
return result;
}
// Driver Code
public static void Main()
{
string str = "MISSISSIPPI";
// Assuming the string and the
// character are all in uppercase
Console.WriteLine(getResult(str, 'S') );
}
}
// This code is contributed by anuj_67
PHP
<?php
// PHP implementation of the approach
// Function to return factorial of
// the number passed as argument
function fact($n)
{
$result = 1;
for ($i = 1; $i <= $n; $i++)
$result *= $i;
return $result;
}
// Function to get the total permutations
// which satisfy the given condition
function getResult($str, $ch)
{
// Create has to store count
// of each character
$has = array_fill(0, 26, NULL);
// Store character occurrences
for ($i = 0; $i < strlen($str); $i++)
$has[ord($str[$i]) - ord('A')]++;
// Count number of times
// Particular character comes
$particular = $has[ord($ch) - ord('A')];
// If particular character isn't
// present in the string then return 0
if ($particular == 0)
return 0;
// Remove count of particular character
$has[ord($ch) - ord('A')] = 0;
// Total length
// of the string
$total = strlen($str);
// Assume all occurrences of
// particular character as a
// single character.
$total = $total - $particular + 1;
// Compute factorial of the length
$result = fact($total);
// Divide by the factorials of
// the no. of occurrences of all
// the characters.
for ($i = 0; $i < 26; $i++)
{
if ($has[$i] > 1)
{
$result = $result / fact($has[$i]);
}
}
// return the result
return $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
?>
JavaScript
<script>
// Javascript implementation of the approach
// Function to return factorial of
// the number passed as argument
function fact(n)
{
let result = 1;
for (let i = 1; i <= n; i++)
result *= i;
return result;
}
// Function to get the total permutations
// which satisfy the given condition
function getResult(str, ch)
{
// Create has to store count
// of each character
let has = new Array(26).fill(null);
// Store character occurrences
for (let i = 0; i < str.length; i++)
has[str.charCodeAt(i) - 'A'.charCodeAt(0)]++;
// Count number of times
// Particular character comes
particular = has[ch.charCodeAt(0) - 'A'.charCodeAt(0)];
// If particular character isn't
// present in the string then return 0
if (particular == 0)
return 0;
// Remove count of particular character
has[ch.charCodeAt(0) - 'A'.charCodeAt(0)] = 0;
// Total length
// of the string
let total = str.length;
// Assume all occurrences of
// particular character as a
// single character.
total = total - particular + 1;
// Compute factorial of the length
let result = fact(total);
// Divide by the factorials of
// the no. of occurrences of all
// the characters.
for (let i = 0; i < 26; i++)
{
if (has[i] > 1)
{
result = result / fact(has[i]);
}
}
// return the result
return result;
}
// Driver Code
let str = "MISSISSIPPI";
// Assuming the string and the character
// are all in uppercase
document.write(getResult(str, 'S') + "<br>");
// This code is contributed by gfgking
</script>
Complexity Analysis:
- Time Complexity: O(n) where n is the size of the string.
- Auxiliary Space: O(1) as constant space is taken.
Similar Reads
Number of ways to form a given String from the given set of Strings Given a string str and an array of strings dictionary[], the task is to find the number of ways str can be formed as a concatenation of strings (any number of times) in a dictionary[]. Examples: Input: str = abab, dictionary[] = { a, b, ab }Output: 4Explanation: There are 4 ways to form string str a
15+ min read
Number of strings which starts and ends with same character after rotations Given a string str, the task is to find the number of strings that start and end with the same character after a rotation at every possible index of the given string. Examples: Input: str = "GeeksforGeeks" Output: 2 Explanation: All possible strings with rotations at every index are: "GeeksforGeeks"
4 min read
Minimum length of string having all permutation of given string. Given a string S where 1\leq length\; of\; S\leq 26 . Assume that all the characters in S are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present as a substring in the resulting
4 min read
Reorder characters of a string to valid English representations of digits Given a string S of length N, consisting of lowercase characters containing reordered English representations of digits [0 - 9], the task is to print those digits in ascending order. Examples: Input: S = "fviefuro"Output: 45Explanation: The given string can be reshuffled to "fourfive", Therefore, th
8 min read
Count of distinct permutation of a String obtained by swapping only unequal characters Given a string find the number of unique permutations that can be obtained by swapping two indices such that the elements at these indices are distinct. NOTE: Swapping is always performed in the original string. Examples: Input: str = "sstt"Output: 5Explanation: Swap str[0] with str[2], string obtai
11 min read