Count of Distinct strings possible by inserting K characters in the original string

• Last Updated : 03 Aug, 2021

Given a string S and an integer K, the task is to find the total number of strings that can be formed by inserting exactly K characters at any position of the string S. Since the answer can be large, print it modulo 109+7.
Examples:

Input: S = “a” K = 1
Output: 51
Explanation:
Since any of the 26 characters can be inserted at before ‘a’ or after ‘a’, a total of 52 possible strings can be formed.
But the string “aa” gets formed twice. Hence count of distinct strings possible is 51.
Input: S = “abc” K = 2
Output: 6376

Approach:
The idea is to find the number of strings that contains the str as a subsequence. Follow the steps below to solve the problem:

1. The total number of strings that can be formed by N characters is 26N.
2. Calculate 26N using Binary Exponentiation.
3. In this problem, only the strings that contain the str as a subsequence needs to be considered.
4. Hence, the final count of strings is given by

(total number of strings) – (number of strings that don’t contain the input string as a sub-sequence)

1. While calculating such strings that don’t contain the str as a subsequence, observe that the length of the prefix of S is a subsequence of the resulting string can be between 0 to |S|-1.
2. For every prefix length from 0 to |S|-1, find the total number of strings that can be formed with such a prefix as a sub-sequence. Then subtract that value from 26N.
3. Hence, the final answer is: Below is the implementation of the above approach:

Javascript


Output:
6376

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up