7.4 Islands of Marked Letters
Devanshi Raut wrote a secret message — a lowercase English string S.
She wants to find special hidden “patterns” inside it.
For any chosen substring T of S, imagine marking every position in S that is covered by any occurrence of T.
That means:
If T appears starting at position i, then all letters from i to i + len(T) - 1 are marked.
Some positions may be marked multiple times — that’s okay, they still count as “marked once”.
After all occurrences of T are marked, the marked cells form groups of contiguous Xs (like continuous patches on a map).
Each such patch is called an island.
For example:
S = "ababaewabaq"
T = "aba"
The marked positions look like this:
XXXXXewXXXq
The X’s appear in 2 separate groups, so substring "aba" produces 2 islands.
Your Task:
Given the string S and an integer K, count how many distinct substrings of S produce exactly K islands.
Constraints
1 <= |s| <= 10^5
1 <= |k| <= |s|
Input Format
S — the given lowercase string. (1 <= |s| <= 10^5 )
K — the required number of islands. (1 <= |k| <= |s|)
Output Format
Output a single integer — the count of distinct substrings that produce exactly K islands.
Example 1
Input:
abaab
2
Output:
3
Explanation:
All the suitable substrings are: a, ab, b.
Log In to solve the Question