CSES Solutions - Creating Strings II
Last Updated :
23 Jul, 2025
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
import java.util.Arrays;
public class Main {
static final long MOD = 1000000007;
// Function to calculate factorial modulo MOD
static long factorial(int n)
{
long result = 1;
for (int i = 2; i <= n; ++i) {
result = (result * i) % MOD;
}
return result;
}
// Function to the calculate modular exponentiation
static long modExp(long base, long exp, long mod)
{
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
static long modInverse(long n, long mod)
{
return modExp(n, mod - 2, mod);
}
public static void main(String[] args)
{
String s = "aabac";
// Count occurrences of each character
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
// Calculate the factorial of the length of the
// string
long ans = factorial(s.length());
// Divide by the factorial of the counts of each
// character
for (int i = 0; i < 26; ++i) {
if (count[i] > 0) {
ans = (ans
* modInverse(factorial(count[i]),
MOD))
% MOD;
}
}
System.out.println(ans);
}
}
Python
MOD = 10**9 + 7
# Function to the calculate factorial modulo MOD
def factorial(n):
result = 1
for i in range(2, n + 1):
result = (result * i) % MOD
return result
# Function to calculate modular exponentiation
def mod_exp(base, exp, mod):
result = 1
while exp > 0:
if exp % 2 == 1:
result = (result * base) % mod
base = (base * base) % mod
exp //= 2
return result
# Function to calculate modular inverse using the Fermat's Little Theorem
def mod_inverse(n, mod):
return mod_exp(n, mod - 2, mod)
# Main function
def main():
s = "aabac"
# Count occurrences of the each character
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
# Calculate the factorial of the length of string
ans = factorial(len(s))
# Divide by the factorial of the counts of the each character
for i in range(26):
if count[i] > 0:
ans = (ans * mod_inverse(factorial(count[i]), MOD)) % MOD
print(ans)
if __name__ == "__main__":
main()
JavaScript
const MOD = BigInt(10**9 + 7);
// Function to calculate the factorial modulo MOD
function factorial(n) {
let result = BigInt(1);
for (let i = BigInt(2); i <= n; i++) {
result = (result * i) % MOD;
}
return result;
}
// Function to calculate modular exponentiation
function modExp(base, exp, mod) {
let result = BigInt(1);
while (exp > 0n) {
if (exp % 2n === 1n) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp = exp / 2n;
}
return result;
}
// Function to calculate modular inverse using Fermat's Little Theorem
function modInverse(n, mod) {
return modExp(n, mod - BigInt(2), mod);
}
// Main function
function main() {
const s = "aabac";
// Count occurrences of each character
const count = Array(26).fill(BigInt(0));
for (let c of s) {
count[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
// Calculate the factorial of the length of the string
let ans = factorial(BigInt(s.length));
// Divide by the factorial of the counts of each character
for (let i = 0; i < 26; i++) {
if (count[i] > BigInt(0)) {
ans = (ans * modInverse(factorial(count[i]), MOD)) % MOD;
}
}
console.log(ans.toString()); // Convert BigInt to string for output
}
main();
// This code is contributed by Shivam Gupta
Time Complexity: O(N logN)
Auxiliary Space: O(N)
Similar Reads
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
UGC NET Computer Science Syllabus 2024 PDF Download UGC NET is a competitive exam that is conducted by NTAs(National Testing Agency). Computer Science and Applications is one of the popular branches of UGC NET. In this article, we are going to discuss the syllabus of Computer Science and Applications and different terms related to Computer Science an
14 min read
Introduction to Flowcharts The flowcharts are simple visual tools that help us understand and represent processes very easily. They use shapes like arrows, rectangles, and diamonds to show steps and decisions clearly. If someone is making a project or explaining a complex task, flowcharts can make complex ideas easier to unde
5 min read
Program to print ASCII Value of a character Given a character, we need to print its ASCII value in C/C++/Java/Python. Examples : Input : a Output : 97 Input : DOutput : 68 Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string o
4 min read
Cryptography Hash Functions Cryptographic hash functions are mathematical algorithms that transform input data into a fixed-length sequence of characters, referred to as a hash value. Cryptographic hash functions are intended to be fast, deterministic, and one-way, meaning that even a minor change in input yields a very differ
6 min read
CSES Problem Set Solutions In this article, we have compiled comprehensive, high-quality tutorials on the CSES Problem Set Solutions to assist you in understanding the problem set for learning algorithmic programming. What is CSES Problem Set?CSES Problem Set is a collection of competitive programming tasks hosted on the CSES
8 min read
Competitive Programming (CP) Handbook with Complete Roadmap Welcome to the Competitive Programming Handbook or CP Handbook by GeeksforGeeks! This Competitive Programming Handbook is a go-to resource for individuals aiming to enhance their problem-solving skills and excel in coding competitions. This CP handbook provides a comprehensive guide, covering fundam
12 min read
Fast I/O for Competitive Programming In competitive programming, it is important to read input as fast as possible so we save valuable time. You must have seen various problem statements saying: " Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)" . The key for such
4 min read
Binary Exponentiation for Competitive Programming In competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills. Table of ContentWhat is Binary
15+ min read
Puzzle | Light all the bulbs Problem Statement: Consider a circle with 2014 light bulbs and only 2 of them are on and the rest are off. Anyone can choose any of the bulbs and change the state of the neighboring bulbs. The task is to switch all the 2014 light bulbs on?Solution: Yes, it is possible to get all the light bulbs ON.F
2 min read