Suppose, we have a string 'i' consisting of lowercase letters and another integer 'j'. We have to find out how many strings there are that are equal to the size of 'i' and are lexicographically smaller or equal to 'i' and having no consecutive equal characters greater than 'j'.
The answer has to calculated by finding the Mod the result by 10 ^ 9 + 7.
So, if the input is like i = "app", j = 2, then the output will be 405.
To solve this, we will follow these steps −
if j <= 0, then
m := 10 ^ 9 + 7
n := size of i
nums := a new list containing (unicode representation of character - unicode representation of "a") for each character present in s
return dp(0, True, -1, 0) mod m
Define a function dp() . This will take pos, bound, last, count
if count > j is non-zero, then
if pos is same as n, then
num := nums[pos]
res := 0
for i in range 0 to (num + 1 if bound, otherwise 26), do
res := res + dp(pos + 1, true if bound and i is same as num, i, count *(true if i is same as last) + 1)
From the main method return dp(0, True, -1, 0) % m
Let us see the following implementation to get better understanding −
class Solution: def solve(self, s, k): if k <= 0: return 0 MOD = 10 ** 9 + 7 n = len(s) nums = [ord(char) - ord("a") for char in s] def dp(pos, bound, last, count): if count > k: return 0 if pos == n: return 1 num = nums[pos] res = 0 for i in range(num + 1 if bound else 26): res += dp(pos + 1, bound and i == num, i, count * (i == last) + 1) return res return dp(0, True, -1, 0) % MOD ob = Solution() print(ob.solve('app',2))
i = "app" j = 2