VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-strings-can-formed-using-b-c-given-constraints/

⇱ Count of strings that can be formed using a, b and c under given constraints - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of strings that can be formed using a, b and c under given constraints

Last Updated : 19 Apr, 2026

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
Explanation:
Number of strings with 3 occurrances of a: 1
2-a and 1-b: 3
2-a and 1-c: 3
1-a, 1-b and 1-c: 6
1-a and 2-c: 3
1-b and 2-c: 3
So, total number of strings of length 3
is 1 + 3 + 3 + 6 + 3 + 3 = 19

Input: n = 1
Output: 3
Explanation: Possible strings are: "a", "b" and "c"

[Naive Approach] Recursion (Generate All Valid Strings) - O(3^n) Time O(n) Space

A simple solution is to recursively build strings by choosing 'a', 'b', or 'c' at each step while keeping track of remaining allowed counts of 'b' and 'c'.


Output
19

[Better Approach] Recursion + Memoization (DP) - O(n) Time O(n) Space

Use recursion with a DP array to store already computed states (n, bCount, cCount) and reuse them to avoid repeated calculations.


Output
19

[Expected Approach] Combinatorics Solution - O(1) Time O(1) Space

The idea is to use 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!)

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' and 'a's?

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 only 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 1 'b' and/or 2 '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 .


Output
19
Comment
Article Tags: