Open In App

CSES Solutions - Creating Strings II

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a string, your task is to calculate the number of different strings that can be created using its characters.

Examples:

Input: S = "aa"
Output: 1
Explanation: There is only 1 possible string: "aa".

Input: S = "aabac"
Output: 20
Explanation: There are 20 possible strings: "aaabc", "aaacb", "aabac", "aabca", "aacab", "aacba", "abaac", "abaca", "abcaa", "acaab", "acaba", "acbaa", "baaac", "baaca", "bacaa", "bcaaa", "caaab", "caaba", "cabaa" and "cbaaa".

Approach: To solve the problem, follow the below idea:

We can use the concept of permutations to solve this problem. Given a string of the length n the number of the different strings that can be created using its characters is n! where n! represents the factorial of the n.

However, since the characters in the given string might be repeated we need to the consider the repetitions. We'll calculate the factorial of the length of string and then divide it by the factorial of the count of the each character's occurrence.

Below is the implementation of the algorithm:

C++
#include <iostream>
#include <vector>
#define MOD 1000000007
using namespace std;
// Function to calculate factorial modulo MOD
long long factorial(int n)
{
    long long result = 1;
    for (int i = 2; i <= n; ++i) {
        result = (result * i) % MOD;
    }
    return result;
}
// Function to the calculate modular exponentiation
long long mod_exp(long long base, long long exp,
                  long long mod)
{
    long long result = 1;
    while (exp > 0) {
        if (exp % 2 == 1) {
            result = (result * base) % mod;
        }
        base = (base * base) % mod;
        exp /= 2;
    }
    return result;
}
// Function to the calculate modular inverse using Fermat's
// Little Theorem
long long mod_inverse(long long n, long long mod)
{
    return mod_exp(n, mod - 2, mod);
}
int main()
{
    string s = "aabac";
    // Count occurrences of each character
    vector<int> count(26, 0);
    for (char c : s) {
        count[c - 'a']++;
    }
    // Calculate the factorial of the length of the string
    long long ans = factorial(s.size());
    // Divide by the factorial of the counts of each
    // character
    for (int i = 0; i < 26; ++i) {
        if (count[i] > 0) {
            ans = (ans
                   * mod_inverse(factorial(count[i]), MOD))
                  % MOD;
        }
    }
    cout << ans << endl;
    return 0;
}
Java Python JavaScript

Output
20

Time Complexity: O(N logN)
Auxiliary Space: O(N)


Next Article

Similar Reads