Given a number n, count the number of strings of length n such that every string has adjacent characters with a difference between ASCII values as 1.
Examples:
Input : N = 1 Output : Total strings are 26 Explanation : For N=1, strings are a, b, c,, ...., x, y, z Input : N = 2 Output : Total strings are 50 Explanation : For N = 2, strings are ab, ba, bc, cb, .., yx, yz, zy
For strings starting with character ‘A’ and length ‘i’, we consider all strings of length ‘i-1’ and starting with character ‘B’
For strings starting with character ‘G’ and length ‘i’, we consider all strings of length ‘i-1’ and starting with character ‘H’ and all strings of length ‘i-1’ and starting with ‘F’.
We take the base case for n = 1, and set result for all 26 characters as 1. This simply means when 1 character string is consider all alphabets from a-z are taken only once.
For N = 2,
For N = 3,
Conclusion : For N = n
countAdjacent(n) dp[i][j] finally stores count of strings of length i and starting with character j. Initialize dp[n+1][27] as 0 Initialize dp[1][j] = 1 where j = 0 to 25 for i = 2 to n for j = 0 to 25 if (j = 0) dp[i][j] = dp[i-1][j+1]; else dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1]; Sum of n-th row from 0 to 25 is the result.
Implementation:
Total strings are : 98
Time Complexity: O(26*n)
Auxiliary Space: O(26*n)