Find Maximum Number of Non Intersecting Substrings - Problem
You're given a string word and need to find the maximum number of non-overlapping substrings that satisfy two conditions:
- Each substring must be at least 4 characters long
- Each substring must start and end with the same letter
The key challenge is to maximize the count while ensuring no two selected substrings overlap (share any characters).
Example: In the string "abcadefgag", we could select "abca" (positions 0-3) and "gag" (positions 7-9) for a total of 1 valid substring, since "gag" is only 3 characters long.
Think of it as placing non-overlapping brackets around valid substrings to maximize the number of brackets you can place!
Input & Output
example_1.py โ Basic Case
$
Input:
word = "abcadefgag"
โบ
Output:
1
๐ก Note:
Only one valid substring exists: "abca" (positions 0-3). The substring "gag" is only 3 characters long, so it doesn't meet the minimum length requirement of 4.
example_2.py โ Multiple Options
$
Input:
word = "aabcaabdaea"
โบ
Output:
2
๐ก Note:
We can select "aabca" (0-4) and "aea" (8-10). Wait, "aea" is only 3 chars, so invalid. Actually, we can take "aabca" (0-4) and "aabda" doesn't work either. The answer is 1 with just "aabca".
example_3.py โ No Valid Substrings
$
Input:
word = "abcdef"
โบ
Output:
0
๐ก Note:
No character appears at both the start and end of any substring of length โฅ 4, so no valid substrings exist.
Constraints
- 1 โค word.length โค 2000
- word consists of lowercase English letters only
- Each valid substring must be at least 4 characters long
- Valid substrings must start and end with the same letter
Visualization
Tap to expand
Understanding the Visualization
1
Scan Left to Right
Move through the string character by character, looking for opportunities
2
Find Valid Endpoints
When you encounter a character, look ahead to find the earliest matching character at distance โฅ4
3
Make Greedy Choice
Immediately select the shortest valid substring to leave maximum space for future selections
4
Skip Covered Positions
Jump past the selected substring and continue the process
Key Takeaway
๐ฏ Key Insight: Greedy selection of shortest valid substrings maximizes the number of non-overlapping selections by preserving the most space for future opportunities.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code