Count of Distinct strings possible by inserting K characters in the original string
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.
Input: S = “a” K = 1
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
The idea is to find the number of strings that contains the str as a subsequence. Follow the steps below to solve the problem:
- The total number of strings that can be formed by N characters is 26N.
- Calculate 26N using Binary Exponentiation.
- In this problem, only the strings that contain the str as a subsequence needs to be considered.
- 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)
- 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.
- 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.
- Hence, the final answer is:
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1)