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
Find Maximum Non-Intersecting Substrings INPUT String: word = "ababa" a 0 b 1 a 2 b 3 a 4 Requirements: • Length >= 4 characters • Start and end same letter • Non-intersecting Candidate Substrings: "ababa" (0-4) "abab" - invalid ALGORITHM STEPS Greedy - Select Earliest Ending 1 Find char positions a: [0,2,4], b: [1,3] 2 Generate valid substrings Same start/end, len >= 4 3 Sort by end index Greedy: earliest ending first 4 Select non-overlapping Pick if start > last end Processing: "ababa" [0-4]: len=5 OK Selected! end_pos = 4 No more non-overlapping FINAL RESULT Selected Substring: a b a b a 5 "ababa" - indices 0 to 4 OUTPUT 1 OK - Verified Max count = 1 Only one valid substring fits all requirements Key Insight: The greedy approach works by sorting valid substrings by their ending index. By always selecting the substring that ends earliest, we maximize the remaining space for additional substrings. For "ababa", the entire string is the only valid substring (length 5, starts/ends with 'a'). TutorialsPoint - Find Maximum Number of Non Intersecting Substrings | Greedy - Select Earliest Ending
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