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

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

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.

  • Time : O(1)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
long long int countStr(long long int n){
if(n == 1) return 3;
if(n == 2) return 8;
long long int res = 0;
for(long long int b = 0; b <= 1; b++) {
for(long long int c = 0; c <= 2; c++) {
if(b == 0 and c == 0) res += 1;
if(b == 0 and c == 1) res += n;
if(b == 0 and c == 2) res += n * (n - 1) / 2;
if(b == 1 and c == 0) res += n;
if(b == 1 and c == 1) res += n * (n - 1);
if(b == 1 and c == 2) res += n * (n - 1) * (n - 2) / 2;
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/count-of-strings-that-can-be-formed-using-a-b-and-c-under-given-constraints/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.