Skip to main content

Find Maximum Number of Non Intersecting Substrings - Solution & Explanation

MediumHash TableStringDynamic ProgrammingGreedy3 min readAsked at: Bloomberg
Practice this problem

Problem Statement

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.

 

Example 1:

Input: word = "abcdeafdef"

Output: 2

Explanation:

The two substrings are "abcdea" and "fdef".

Example 2:

Input: word = "bcdaaaab"

Output: 1

Explanation:

The only substring is "aaaa". Note that we cannot also choose "bcdaaaab" since it intersects with the other substring.

 

Constraints:

  • 1 <= word.length <= 2 * 105
  • word consists only of lowercase English letters.

Approach Overview

Problem Overview: Given a string s, return the maximum number of substrings that do not overlap such that every character inside a chosen substring appears only within that substring in the entire string. Among all valid sets, the solution prefers the set with the maximum count of substrings.

Approach 1: Brute Force Substring Validation (O(n^3) time, O(1) space)

Enumerate every possible substring using two nested loops. For each candidate substring s[i..j], scan the whole string to verify that every character inside the substring does not appear outside the interval. After collecting all valid substrings, sort them by ending index and greedily pick non‑overlapping ones. This approach performs repeated scans of the string, leading to cubic complexity. Useful only for understanding the constraint that every character's global occurrences must lie inside the chosen interval.

Approach 2: Character Range Expansion (Greedy + Hash Table) (O(26 * n) ≈ O(n) time, O(1) space)

Precompute the first and last occurrence of each character using a hash table or fixed array of size 26. For every character's first occurrence, treat its interval [start, end] as a candidate substring. Expand the interval by iterating from start to end; if a character inside has a last occurrence beyond end, extend the boundary. If any character inside appears before start, the interval is invalid and must be discarded. Valid intervals represent minimal substrings that contain all occurrences of their characters. Collect these intervals and select the maximum number of non-overlapping ones by sorting by end index and greedily choosing the earliest finishing interval. This leverages ideas from greedy interval scheduling combined with string preprocessing.

Approach 3: Dynamic Programming with Interval Candidates (O(n + k log k) time, O(k) space)

After generating all valid minimal intervals using the expansion method, treat them as interval scheduling candidates. Use dynamic programming or greedy selection based on sorted end indices. DP can track the maximum number of substrings achievable up to each interval while ensuring non-overlap. In practice, the greedy strategy (pick the earliest ending valid substring) already yields the optimal result because minimal intervals never partially overlap in a way that benefits delaying the choice.

Recommended for interviews: The interval expansion + greedy selection approach is what interviewers expect. It demonstrates understanding of character frequency boundaries, interval construction, and classic greedy scheduling. Starting with brute force shows the constraint clearly, but the optimized O(n) solution proves you can combine preprocessing with greedy reasoning efficiently.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Substring ValidationO(n^3)O(1)Understanding the constraint that all occurrences of characters must stay inside the chosen substring
Character Range Expansion + GreedyO(n)O(1)Optimal general solution; builds minimal valid intervals and selects non-overlapping ones
DP with Interval CandidatesO(n + k log k)O(k)Useful when modeling as interval scheduling or extending to weighted variants

Video Solution

3557. Find Maximum Number of Non Intersecting Substrings | Biweekly Contest 157 | Leetcode • Rapid Syntax • 636 views views

Watch 6 more video solutions →

Frequently Asked Questions

Is Find Maximum Number of Non Intersecting Substrings easy or hard?
This problem is generally classified as Medium difficulty. The challenge lies in recognizing that each character defines a dependency range and that valid substrings must include all occurrences of their characters. Once intervals are constructed correctly, the remaining step becomes a standard greedy interval selection problem.
Find Maximum Number of Non Intersecting Substrings Python/Java solution
Python and Java implementations typically compute two arrays for first and last character positions, then iterate through the string to expand valid intervals. Candidate intervals are validated and added to the result using greedy selection by end index. The overall implementation remains O(n) time and constant space.
How to solve Find Maximum Number of Non Intersecting Substrings in O(n)?
Store the first and last occurrence of each character. For every character's first position, attempt to build a minimal valid substring by expanding the right boundary whenever a character inside has a later last occurrence. If a character inside appears before the start index, discard the interval. Collect all valid intervals and greedily choose the earliest finishing ones to maximize the count.
What is the best approach for Find Maximum Number of Non Intersecting Substrings?
The optimal approach uses character range expansion with a greedy interval selection strategy. First compute the first and last occurrence of each character. Expand intervals to ensure every character inside the substring appears only within that interval. After generating valid intervals, sort by ending index and greedily choose non-overlapping substrings. This runs in O(n) time with constant extra space.
Is Find Maximum Number of Non Intersecting Substrings asked at Google/Amazon/Meta?
Problems involving interval construction, greedy scheduling, and string boundary expansion frequently appear in interviews at companies like Google, Amazon, and Meta. Variants test the ability to convert character frequency constraints into intervals and apply greedy selection. The pattern is closely related to interval scheduling and partition-label style problems.
What data structure is used in Find Maximum Number of Non Intersecting Substrings?
The solution primarily uses arrays or hash tables to store the first and last occurrence of characters. After computing these ranges, intervals are processed using greedy logic similar to interval scheduling. No complex structures are required beyond simple arrays and sorting.
What is the time complexity of Find Maximum Number of Non Intersecting Substrings?
The optimized solution runs in O(n) time where n is the length of the string. Each character is processed while expanding intervals and building candidate substrings, and the alphabet size (26) keeps preprocessing constant. Space complexity is O(1) because only fixed-size arrays for character positions are required.

Ready to solve this problem?

Practice Find Maximum Number of Non Intersecting Substrings with our built-in code editor and test cases.

Practice on FleetCode