Count of strings that can be formed using a, b and c under given constraints
Last Updated :
14 Dec, 2022
Given a length n, count the number of strings of length n that can be made using 'a', 'b' and 'c' with at most one 'b' and two 'c's allowed.
Examples :
Input : n = 3
Output : 19
Below strings follow given constraints:
aaa aab aac aba abc aca acb acc baa
bac bca bcc caa cab cac cba cbc cca ccb
Input : n = 4
Output : 39
Asked in Google Interview
A simple solution is to recursively count all possible combinations of strings that can be made up to latter 'a', 'b', and 'c'.
Below is the implementation of the above idea
C++
// C++ program to count number of strings
// of n characters with
#include<bits/stdc++.h>
using namespace std;
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStr(int n, int bCount, int cCount)
{
// Base cases
if (bCount < 0 || cCount < 0) return 0;
if (n == 0) return 1;
if (bCount == 0 && cCount == 0) return 1;
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStr(n-1, bCount, cCount);
res += countStr(n-1, bCount-1, cCount);
res += countStr(n-1, bCount, cCount-1);
return res;
}
// Driver code
int main()
{
int n = 3; // Total number of characters
cout << countStr(n, 1, 2);
return 0;
}
Java
// Java program to count number
// of strings of n characters with
import java.io.*;
class GFG
{
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
static int countStr(int n,
int bCount,
int cCount)
{
// Base cases
if (bCount < 0 || cCount < 0) return 0;
if (n == 0) return 1;
if (bCount == 0 && cCount == 0) return 1;
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStr(n - 1, bCount, cCount);
res += countStr(n - 1, bCount - 1, cCount);
res += countStr(n - 1, bCount, cCount - 1);
return res;
}
// Driver code
public static void main (String[] args)
{
int n = 3; // Total number of characters
System.out.println(countStr(n, 1, 2));
}
}
// This code is contributed by akt_mit
Python 3
# Python 3 program to
# count number of strings
# of n characters with
# n is total number of characters.
# bCount and cCount are counts
# of 'b' and 'c' respectively.
def countStr(n, bCount, cCount):
# Base cases
if (bCount < 0 or cCount < 0):
return 0
if (n == 0) :
return 1
if (bCount == 0 and cCount == 0):
return 1
# Three cases, we choose, a or b or c
# In all three cases n decreases by 1.
res = countStr(n - 1, bCount, cCount)
res += countStr(n - 1, bCount - 1, cCount)
res += countStr(n - 1, bCount, cCount - 1)
return res
# Driver code
if __name__ =="__main__":
n = 3 # Total number of characters
print(countStr(n, 1, 2))
# This code is contributed
# by ChitraNayal
C#
// C# program to count number
// of strings of n characters
// with a, b and c under given
// constraints
using System;
class GFG
{
// n is total number of
// characters. bCount and
// cCount are counts of
// 'b' and 'c' respectively.
static int countStr(int n,
int bCount,
int cCount)
{
// Base cases
if (bCount < 0 || cCount < 0)
return 0;
if (n == 0) return 1;
if (bCount == 0 && cCount == 0)
return 1;
// Three cases, we choose,
// a or b or c. In all three
// cases n decreases by 1.
int res = countStr(n - 1,
bCount, cCount);
res += countStr(n - 1,
bCount - 1, cCount);
res += countStr(n - 1,
bCount, cCount - 1);
return res;
}
// Driver code
static public void Main ()
{
// Total number
// of characters
int n = 3;
Console.WriteLine(countStr(n, 1, 2));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP program to count number of
// strings of n characters with
// n is total number of characters.
// bCount and cCount are counts
// of 'b' and 'c' respectively.
function countStr($n, $bCount,
$cCount)
{
// Base cases
if ($bCount < 0 ||
$cCount < 0)
return 0;
if ($n == 0)
return 1;
if ($bCount == 0 &&
$cCount == 0)
return 1;
// Three cases, we choose,
// a or b or c. In all three
// cases n decreases by 1.
$res = countStr($n - 1,
$bCount,
$cCount);
$res += countStr($n - 1,
$bCount - 1,
$cCount);
$res += countStr($n - 1,
$bCount,
$cCount - 1);
return $res;
}
// Driver code
$n = 3; // Total number
// of characters
echo countStr($n, 1, 2);
// This code is contributed by ajit
?>
JavaScript
<script>
// JavaScript program for the above approach
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
function countStr(n, bCount, cCount)
{
// Base cases
if (bCount < 0 || cCount < 0) return 0;
if (n == 0) return 1;
if (bCount == 0 && cCount == 0) return 1;
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
let res = countStr(n - 1, bCount, cCount);
res += countStr(n - 1, bCount - 1, cCount);
res += countStr(n - 1, bCount, cCount - 1);
return res;
}
// Driver Code
let n = 3; // Total number of characters
document.write(countStr(n, 1, 2));
// This code is contributed by splevel62.
</script>
Time Complexity: O(3^N).
Auxiliary Space: O(1).
Efficient Solution:
If we drown a recursion tree of the above code, we can notice that the same values appear multiple times. So we store results that are used later if repeated.
C++
// C++ program to count number of strings
// of n characters with
#include<bits/stdc++.h>
using namespace std;
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
int countStrUtil(int dp[][2][3], int n, int bCount=1,
int cCount=2)
{
// Base cases
if (bCount < 0 || cCount < 0) return 0;
if (n == 0) return 1;
if (bCount == 0 && cCount == 0) return 1;
// if we had saw this combination previously
if (dp[n][bCount][cCount] != -1)
return dp[n][bCount][cCount];
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStrUtil(dp, n-1, bCount, cCount);
res += countStrUtil(dp, n-1, bCount-1, cCount);
res += countStrUtil(dp, n-1, bCount, cCount-1);
return (dp[n][bCount][cCount] = res);
}
// A wrapper over countStrUtil()
int countStr(int n)
{
int dp[n+1][2][3];
memset(dp, -1, sizeof(dp));
return countStrUtil(dp, n);
}
// Driver code
int main()
{
int n = 3; // Total number of characters
cout << countStr(n);
return 0;
}
Java
// Java program to count number of strings
// of n characters with
class GFG
{
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
static int countStrUtil(int[][][] dp, int n,
int bCount, int cCount)
{
// Base cases
if (bCount < 0 || cCount < 0)
{
return 0;
}
if (n == 0)
{
return 1;
}
if (bCount == 0 && cCount == 0)
{
return 1;
}
// if we had saw this combination previously
if (dp[n][bCount][cCount] != -1)
{
return dp[n][bCount][cCount];
}
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStrUtil(dp, n - 1, bCount, cCount);
res += countStrUtil(dp, n - 1, bCount - 1, cCount);
res += countStrUtil(dp, n - 1, bCount, cCount - 1);
return (dp[n][bCount][cCount] = res);
}
// A wrapper over countStrUtil()
static int countStr(int n, int bCount, int cCount)
{
int[][][] dp = new int[n + 1][2][3];
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
dp[i][j][k] = -1;
}
}
}
return countStrUtil(dp, n,bCount,cCount);
}
// Driver code
public static void main(String[] args)
{
int n = 3; // Total number of characters
int bCount = 1, cCount = 2;
System.out.println(countStr(n,bCount,cCount));
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python 3 program to count number of strings
# of n characters with
# n is total number of characters.
# bCount and cCount are counts of 'b'
# and 'c' respectively.
def countStrUtil(dp, n, bCount=1,cCount=2):
# Base cases
if (bCount < 0 or cCount < 0):
return 0
if (n == 0):
return 1
if (bCount == 0 and cCount == 0):
return 1
# if we had saw this combination previously
if (dp[n][bCount][cCount] != -1):
return dp[n][bCount][cCount]
# Three cases, we choose, a or b or c
# In all three cases n decreases by 1.
res = countStrUtil(dp, n-1, bCount, cCount)
res += countStrUtil(dp, n-1, bCount-1, cCount)
res += countStrUtil(dp, n-1, bCount, cCount-1)
dp[n][bCount][cCount] = res
return dp[n][bCount][cCount]
# A wrapper over countStrUtil()
def countStr(n):
dp = [ [ [-1 for x in range(2+1)] for y in range(1+1)]for z in range(n+1)]
return countStrUtil(dp, n)
# Driver code
if __name__ == "__main__":
n = 3 # Total number of characters
print(countStr(n))
# This code is contributed by chitranayal
C#
// C# program to count number of strings
// of n characters with
using System;
class GFG
{
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
static int countStrUtil(int[,,] dp, int n,
int bCount=1, int cCount=2)
{
// Base cases
if (bCount < 0 || cCount < 0)
return 0;
if (n == 0)
return 1;
if (bCount == 0 && cCount == 0)
return 1;
// if we had saw this combination previously
if (dp[n,bCount,cCount] != -1)
return dp[n,bCount,cCount];
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStrUtil(dp, n - 1, bCount, cCount);
res += countStrUtil(dp, n - 1, bCount - 1, cCount);
res += countStrUtil(dp, n - 1, bCount, cCount - 1);
return (dp[n, bCount, cCount] = res);
}
// A wrapper over countStrUtil()
static int countStr(int n)
{
int[,,] dp = new int[n + 1, 2, 3];
for(int i = 0; i < n + 1; i++)
for(int j = 0; j < 2; j++)
for(int k = 0; k < 3; k++)
dp[i, j, k] = -1;
return countStrUtil(dp, n);
}
// Driver code
static void Main()
{
int n = 3; // Total number of characters
Console.Write(countStr(n));
}
}
// This code is contributed by DrRoot_
JavaScript
<script>
// javascript program to count number of strings
// of n characters with
// n is total number of characters.
// bCount and cCount are counts of 'b'
// and 'c' respectively.
function countStrUtil(dp , n, bCount , cCount)
{
// Base cases
if (bCount < 0 || cCount < 0)
{
return 0;
}
if (n == 0)
{
return 1;
}
if (bCount == 0 && cCount == 0)
{
return 1;
}
// if we had saw this combination previously
if (dp[n][bCount][cCount] != -1)
{
return dp[n][bCount][cCount];
}
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
var res = countStrUtil(dp, n - 1, bCount, cCount);
res += countStrUtil(dp, n - 1, bCount - 1, cCount);
res += countStrUtil(dp, n - 1, bCount, cCount - 1);
return (dp[n][bCount][cCount] = res);
}
// A wrapper over countStrUtil()
function countStr(n , bCount , cCount)
{
dp = Array(n+1).fill(0).map
(x => Array(2).fill(0).map
(x => Array(3).fill(0)));
for (i = 0; i < n + 1; i++)
{
for (j = 0; j < 2; j++)
{
for (k = 0; k < 3; k++)
{
dp[i][j][k] = -1;
}
}
}
return countStrUtil(dp, n,bCount,cCount);
}
// Driver code
var n = 3; // Total number of characters
var bCount = 1, cCount = 2;
document.write(countStr(n,bCount,cCount));
// This code contributed by shikhasingrajput
</script>
Time Complexity : O(n)
Auxiliary Space : O(n)
Thanks to Mr. Lazy for suggesting above solutions.
A solution that works in O(1) time :
We can apply the concepts of combinatorics to solve this problem in constant time. we may recall the formula that the number of ways we can arrange a total of n objects, out of which p number of objects are of one type, q objects are of another type, and r objects are of the third type is n!/(p!q!r!)
Let us proceed towards the solution step by step.
How many strings we can form with no 'b' and 'c'? The answer is 1 because we can arrange a string consisting of only 'a' in one way only and the string would be aaaa....(n times).
How many strings we can form with one 'b'? The answer is n because we can arrange a string consisting (n-1) 'a's and 1 'b' is n!/(n-1)! = n . The same goes for 'c' .
How many strings we can form with 2 places, filled up by 'b' and/or 'c' ? Answer is n*(n-1) + n*(n-1)/2 . Because that 2 places can be either 1 'b' and 1 'c' or 2 'c' according to our given constraints. For the first case, total number of arrangements is n!/(n-2)! = n*(n-1) and for second case that is n!/(2!(n-2)!) = n*(n-1)/2 .
Finally, how many strings we can form with 3 places, filled up by 'b' and/or 'c' ? Answer is (n-2)*(n-1)*n/2 . Because those 3 places can only be consisting of 1 'b' and 2'c' according to our given constraints. So, total number of arrangements is n!/(2!(n-3)!) = (n-2)*(n-1)*n/2 .
Implementation:
C++
// A O(1) CPP program to find number of strings
// that can be made under given constraints.
#include<bits/stdc++.h>
using namespace std;
int countStr(int n){
int count = 0;
if(n>=1){
//aaa...
count += 1;
//b...aaa...
count += n;
//c...aaa...
count += n;
if(n>=2){
//bc...aaa...
count += n*(n-1);
//cc...aaa...
count += n*(n-1)/2;
if(n>=3){
//bcc...aaa...
count += (n-2)*(n-1)*n/2;
}
}
}
return count;
}
// Driver code
int main()
{
int n = 3;
cout << countStr(n);
return 0;
}
Java
// A O(1) Java program to
// find number of strings
// that can be made under
// given constraints.
import java.io.*;
class GFG
{
static int countStr(int n)
{
return 1 + (n * 2) +
(n * ((n * n) - 1) / 2);
}
// Driver code
public static void main (String[] args)
{
int n = 3;
System.out.println( countStr(n));
}
}
// This code is contributed by ajit
Python 3
# A O(1) Python3 program to find
# number of strings that can be
# made under given constraints.
def countStr(n):
return (1 + (n * 2) +
(n * ((n * n) - 1) // 2))
# Driver code
if __name__ == "__main__":
n = 3
print(countStr(n))
# This code is contributed
# by ChitraNayal
C#
// A O(1) C# program to
// find number of strings
// that can be made under
// given constraints.
using System;
class GFG
{
static int countStr(int n)
{
return 1 + (n * 2) +
(n * ((n * n) - 1) / 2);
}
// Driver code
static public void Main ()
{
int n = 3;
Console.WriteLine(countStr(n));
}
}
// This code is contributed by m_kit
PHP
<?php
// A O(1) PHP program to find
// number of strings that can
// be made under given constraints.
function countStr($n)
{
return 1 + ($n * 2) + ($n *
(($n * $n) - 1) / 2);
}
// Driver code
$n = 3;
echo countStr($n);
// This code is contributed by aj_36
?>
JavaScript
<script>
// A O(1) javascript program to
// find number of strings
// that can be made under
// given constraints.
function countStr(n) {
return 1 + (n * 2) + (n * ((n * n) - 1) / 2);
}
// Driver code
var n = 3;
document.write(countStr(n));
// This code is contributed by Princi Singh
</script>
Time Complexity : O(1)
Auxiliary Space : O(1)
Thanks to Niharika Sahai for providing above solution.
Similar Reads
Count of Substrings that can be formed without using the given list of Characters
Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given s
7 min read
Check if it is possible to form string B from A under the given constraints
Given two strings A and B and two integers b and m. The task is to find that if it is possible to form string B from A such that A is divided into groups of b characters except the last group which will have characters ? b and you are allowed to pick atmost m characters from each group, and also ord
9 min read
Number of words that can be made using exactly P consonants and Q vowels from the given string
Given a string str and two integers P and Q. The task is to find the total count of words that can be formed by choosing exactly P consonants and Q vowels from the given string.Examples: Input: str = "geek", P = 1, Q = 1 Output: 8 "ge", "ge", "eg", "ek", "eg", "ek", "ke" and "ke" are the possible wo
7 min read
Count of substrings formed using a given set of characters only
Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = "abcb", K = 2, charArray[] = {'a', '
8 min read
Count of substrings of a string containing another given string as a substring
Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3] = âabcâS[0, 3] = âdabcâ Input: S
8 min read
Count of strings that does not contain any character of a given string
Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Check if characters of a given string can be used to form any N equal strings
Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No. Examples: Input: S = "caacbb", N = 2Output: YesExplanation: All possible strings that can be gen
5 min read
Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
Given two integers A and B, the task is to generate and print a string str such that: str must only contain the characters 'a' and 'b'.str has length A + B and the occurrence of the character 'a' is equal to A and the occurrence of character 'b' is equal to BThe sub-strings "aaa" or "bbb" must not o
6 min read
Count of strings that can be formed from another string using each character at-most once
Given two strings str1 and str2, the task is to print the number of times str2 can be formed using characters of str1. However, a character at any index of str1 can only be used once in the formation of str2. Examples: Input: str1 = "arajjhupoot", str2 = "rajput" Output: 1 Explanation:str2 can only
10 min read
Count of sub-strings that do not consist of the given character
Given a string str and a character c. The task is to find the number of sub-strings that do not consist of the character c. Examples: Input: str = "baa", c = 'b' Output: 3 The sub-strings are "a", "a" and "aa" Input: str = "ababaa", C = 'b' Output: 5 Approach: Initially take a counter that counts th
12 min read