Find Maximum Number of Non Intersecting Substrings - Problem

You are given a string word. Return the maximum number of non-intersecting substrings of word that are at least four characters long and start and end with the same letter.

A substring is non-intersecting if it does not overlap with any other selected substring. The goal is to maximize the count of such valid substrings.

Input & Output

Example 1 — Basic Case
$ Input: word = "ababa"
Output: 1
💡 Note: Valid substrings: "abab" (0-3), "baba" (1-4), "ababa" (0-4). Only one can be selected since they all overlap. Maximum count is 1.
Example 2 — Multiple Non-overlapping
$ Input: word = "abcabc"
Output: 1
💡 Note: Valid substrings: "abca" (0-3), "bcab" (1-4), "cabc" (2-5). They all overlap, so maximum count is 1.
Example 3 — No Valid Substrings
$ Input: word = "abcd"
Output: 0
💡 Note: No substring of length ≥ 4 starts and ends with the same character. Return 0.

Constraints

  • 1 ≤ word.length ≤ 1000
  • word consists of lowercase English letters

Visualization

Tap to expand
Maximum Non-Intersecting Substrings: "ababa" → 1ababaStep 1: Find All Valid SubstringsababbabaababaStep 2: Check OverlapsAll three substrings overlap with each otherCan only select maximum of 1 substringOutput: Maximum count = 1
Understanding the Visualization
1
Input
String with potential valid substrings
2
Find Valid
Identify all substrings ≥4 chars with same start/end letter
3
Select Non-overlapping
Choose maximum count of non-intersecting substrings
Key Takeaway
🎯 Key Insight: Transform string problem into interval scheduling - maximize non-overlapping intervals
Asked in
Google 25 Amazon 20 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen