# Count of N length Strings having S as a Subsequence

• Last Updated : 23 May, 2022

Given a string S and an integer N, the task is to calculate the number of strings of length N consisting of only lowercase characters which have S as one of its subsequences.

Note: As the answer can be very large return it modulo 10^9+7.

Examples:

Input: N = 3, S = “abc”
Output: 1
Explanation: There are  only 1 subsequences of length 3 which is “abc”.

Input: N = 5, S = “aba”
Output: 6376

Approach: This problem can be solved based on the following observation:

Assume, the length of string S (say X) is less at most N. Then the first occurrence of S in any string must end between [X, N].

• Now, suppose the first occurrence of S ends at index i (where X â‰¤ i â‰¤ N), then we can place any character between [i+1, N]. The number of ways to do it is 26N-i.
• Now, the Number of ways to end the first occurrence of string S at ith index is i-1CX-1 * 25i-X * 26N-i  because of the following reason:
• If the last character of S is at ith index then X-1 characters must be placed in the first i-1 positions.
• Number of ways to choose X-1 indices to place the first X-1 characters of the string S before ith index is i-1CX-1 .
• So each of the remaining i-X positions can be filled by any of the 25 characters other than the last character of S (because if the last character of S is chosen then the last character of S will be before i which is not consistent with the assumption).Therefore the number of ways for this is 25i-X.
• So, the total number of ways such that S end at ith index is i-1CX-1 * 25i-X * 26N-i.

Follow the steps mentioned below to solve the problem using the above observation:

• Iterate from i = X to N:
• Assume that S is ending at i.
• Calculate the number of possible ways for this as per the above formula.

Below is the implementation of the above approach:

## Javascript



Output

6376

Time Complexity: O(N * logN)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :