Talentd
FleetCode
Make and follow sheets.Sign in

Maximum Number of Non-Overlapping Substrings solution and explanation

HardGreedyString6 min read65.0% acceptanceUpdated 23 Mar 2026
Maximum Number of Non-Overlapping Substrings | LeetCode 1520 | Coders CampCoders Camp · 17:21 · 7K viewsWatch on YouTube
9 more videos on this problem
  1. Maximum Number of Non-Overlapping Substrings | LeetCode 1520 | Coders CampCoders Camp · 17:21 · 7K views
  2. LeetCode 1520. Maximum Number of Non-Overlapping SubstringsHappy Coding · 38:38 · 6K views
  3. 花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings - 刷题找工作 EP344Hua Hua · 24:59 · 2K views
  4. 1520. Maximum Number of Non-Overlapping Substrings (Leetcode Medium)Programming Live with Larry · 37:12 · 1K views
  5. Leetcode 1520. Maximum Number of Non-Overlapping SubstringsFearless Learner · 14:15 · 539 views
  6. Maximum Number of Non Overlapping Substrings LeetCode solution explainedCodePulse · 23:14 · 528 views
  7. 【每日一题】1520. Maximum Number of Non-Overlapping Substrings, 8/4/2020Huifeng Guan · 31:40 · 423 views
  8. 1520. Maximum Number of Non Overlapping SubstringsMuerde un zombie · 21:58 · 268 views
  9. LeetCode Hard: 1520. Maximum Number of Non Overlapping Substringsrobzingcod · 45:08 · 102 views
  10. LeetCode 1520: Maximum Number of Non-Overlapping SubstringsAlitaCode · 30:48 · 79 views

The problem

Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:

  1. The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.
  2. A substring that contains a certain character c must also contain all occurrences of c.

Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.

Notice that you can return the substrings in any order.

Example 1:

Input: s = "adefaddaccc"
Output: ["e","f","ccc"]
Explanation: The following are all the possible substrings that meet the conditions:
[
  "adefaddaccc"
  "adefadda",
  "ef",
  "e",
  "f",
  "ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.

Example 2:

Input: s = "abbaccd"
Output: ["d","bb","cc"]
Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.

Constraints:

  • 1 <= s.length <= 105
  • s contains only lowercase English letters.

Approach overview

Problem Overview: Given a string s, return the maximum number of non-overlapping substrings such that if a character appears in a substring, all occurrences of that character in the entire string are contained within that substring. Among all valid answers, choose the set with the smallest total length.

The constraint forces each chosen substring to fully cover the first and last occurrence of every character inside it. The main challenge is identifying valid character ranges and then selecting a set of non-overlapping segments that maximizes the count.

Approach 1: Interval Merging (O(n) time, O(1) space)

Start by computing the first and last occurrence of every character in the string. For each character's starting index, attempt to expand its interval until it contains the full range of every character appearing inside it. This works similarly to interval expansion: scan from the start index to the current right boundary and update the boundary if another character extends further. If the expansion reaches a character whose first occurrence is before the starting index, the interval is invalid and must be skipped.

After generating all valid intervals, select non-overlapping ones while minimizing total length. Sort or process them by their right boundary and merge overlapping segments accordingly. Because the alphabet size is limited (26 lowercase letters), the interval construction and checks remain linear. This approach relies heavily on interval reasoning over characters in a string.

Approach 2: Greedy Segment Selection (O(n) time, O(1) space)

A more direct method builds valid segments and selects them greedily. First compute arrays for the first and last position of each character. For each index that equals the first occurrence of its character, try constructing the minimal valid substring by expanding the right boundary while scanning forward. During expansion, if a character appears whose first occurrence lies before the current start, the segment becomes invalid.

If the segment is valid, compare it with the previously chosen substring. When intervals overlap, prefer the one with the smaller right boundary since it leaves more room for future selections. This greedy rule maximizes the total number of substrings. The algorithm performs a single pass over the string and constant-size character tracking, making it efficient for large inputs. This strategy combines interval reasoning with a greedy selection pattern commonly used in substring segmentation problems.

Recommended for interviews: The greedy segment selection approach is typically expected. It demonstrates that you can derive valid character ranges and apply a greedy rule to maximize non-overlapping intervals. Discussing interval construction first shows clear understanding of the underlying string structure, while the greedy selection proves you can optimize the final result.

Approach 1: Interval Merging

In this approach, we first collect the first and last occurrence of each character in the string. Using this data, we create intervals, and then merge them to find non-overlapping intervals that contain all occurrences of every character within those intervals. Finally, we select the smallest non-overlapping intervals to ensure maximum substrings with minimum length are chosen.

def maxNumOfSubstrings(s):
    first, last = {}, {}
    for i, c in enumerate(s):
        if c not in first:
            first[c] = i
        last[c] = i
    
    intervals = []
    for i in range(len(s)):
        if i == first[s[i]]:
            end = last[s[i]]
            j = i
            while j <= end:
                end = max(end, last[s[j]])
                j += 1
            intervals.append((i, end))
            
    intervals.sort(key = lambda x: x[1])
    ans, prev_end = [], -1
    for i, j in intervals:
        if i > prev_end:
            ans.append(s[i:j+1])
            prev_end = j
    return ans

s = "adefaddaccc"
print(maxNumOfSubstrings(s))
import java.util.*;

public class MaxNonOverlap {
    public List<String> maxNumOfSubstrings(String s) {
        int[] start = new int[26];
        int[] end = new int[26];
        Arrays.fill(start, Integer.MAX_VALUE);
        Arrays.fill(end, Integer.MIN_VALUE);

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            start[c - 'a'] = Math.min(start[c - 'a'], i);
            end[c - 'a'] = Math.max(end[c - 'a'], i);
        }

        List<int[]> intervals = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            if (i == start[s.charAt(i) - 'a']) {
                int j = i;
                int right = end[s.charAt(i) - 'a'];
                while (j <= right) {
                    right = Math.max(right, end[s.charAt(j) - 'a']);
                    j++;
                }
                intervals.add(new int[]{i, right});
            }
        }

        intervals.sort((a, b) -> Integer.compare(a[1], b[1]));

        List<String> result = new ArrayList<>();
        int lastEnd = -1;
        for (int[] interval : intervals) {
            if (interval[0] > lastEnd) {
                result.add(s.substring(interval[0], interval[1] + 1));
                lastEnd = interval[1];
            }
        }

        return result;
    }

    public static void main(String[] args) {
        MaxNonOverlap obj = new MaxNonOverlap();
        System.out.println(obj.maxNumOfSubstrings("adefaddaccc"));
    }
}

We first build dictionaries to store the first and last position of each character. Then, we create non-overlapping intervals by scanning through each start of a potential substring and finding its end such that all characters' occurrences are included between the indices. These intervals are sorted and processed to get the maximum that are non-overlapping.

Complexity

Time Complexity: O(n), where n is the length of the string as we traverse the string a constant number of times. Space Complexity: O(1), aside from the result array, as the character count is constant with respect to the input size due to the alphabet limited to lowercase English letters.

Try this approach in the editor

Approach 2: Greedy Segment Selection

This greedy approach involves finding intervals for each character based on their first and last appearance, collecting minimum range intervals that fulfill all character occurrence criteria, and then sorting by ends. The intervals are picked so they are non-overlapping and minimal in length, resulting in maximum substring count with minimum overlapping checks.

function maxNumOfSubstrings(s) {
    const n = s.length;
    const first = Array(26).fill(Infinity);
    const last = Array(26).fill(-Infinity);
    const codeA = 'a'.charCodeAt(0);

    for (let i = 0; i < n; i++) {
        const charIdx = s.charCodeAt(i) - codeA;
        if (first[charIdx] === Infinity) first[charIdx] = i;
        last[charIdx] = i;
    }

    const intervals = [];
    for (let i = 0; i < n; i++) {
        if (i === first[s.charCodeAt(i) - codeA]) {
            let j = i;
            let right = last[s.charCodeAt(i) - codeA];
            while (j <= right) {
                right = Math.max(right, last[s.charCodeAt(j) - codeA]);
                j++;
            }
            intervals.push([i, right]);
        }
    }

    intervals.sort((a, b) => a[1] - b[1]);

    const res = [];
    let lastEnd = -1;
    for (const [start, end] of intervals) {
        if (start > lastEnd) {
            res.push(s.substring(start, end + 1));
            lastEnd = end;
        }
    }

    return res;
}

const result = maxNumOfSubstrings("abbaccd");
console.log(result);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare(const void *a, const void *b) {
    return ((int*)a)[1] - ((int*)b)[1];
}

char** maxNumOfSubstrings(char* s, int* returnSize) {
    int len = strlen(s);
    int start[26];
    int end[26];
    for(int i = 0; i < 26; i++) {
        start[i] = len;
        end[i] = -1;
    }

    for(int i = 0; i < len; i++) {
        int c = s[i] - 'a';
        start[c] = start[c] < i ? start[c] : i;
        end[c] = end[c] > i ? end[c] : i;
    }

    int intervals[len][2];
    int count = 0;
    for(int i = 0; i < len; i++) {
        if(i == start[s[i] - 'a']) {
            int j = i;
            int right = end[s[i] - 'a'];
            while(j <= right) {
                right = right > end[s[j] - 'a'] ? right : end[s[j] - 'a'];
                j++;
            }
            intervals[count][0] = i;
            intervals[count++][1] = right;
        }
    }

    qsort(intervals, count, sizeof(intervals[0]), compare);

    char** res = malloc(len * sizeof(char*));
    *returnSize = 0;
    int lastEnd = -1;
    for(int i = 0; i < count; i++) {
        if(intervals[i][0] > lastEnd) {
            int length = intervals[i][1] - intervals[i][0] + 1;
            res[*returnSize] = malloc((length+1) * sizeof(char));
            strncpy(res[*returnSize], s + intervals[i][0], length);
            res[*returnSize][length] = '\0';
            (*returnSize)++;
            lastEnd = intervals[i][1];
        }
    }

    return res;
}

int main() {
    int returnSize;
    char s[] = "abbaccd";
    char** result = maxNumOfSubstrings(s, &returnSize);
    printf("Output: [");
    for(int i = 0; i < returnSize; i++) {
        printf("%s%s", result[i], (i == returnSize - 1) ? "" : ", ");
        free(result[i]);
    }
    printf("]\n");
    free(result);
}

This JavaScript solution organizes tracking with arrays for first and last indices of characters. Greedy selection is enforced by interval merging and sorting, then finalizing valid choices by ensuring no intervals overlap, hence choosing smallest viable segments.

Complexity

Time Complexity: O(n log n) due to sorting required on possible intervals. Space Complexity: O(n) due to interval and result storage.

Try this approach in the editor

Complexity comparison

ApproachComplexity
Interval Merging

Time Complexity: O(n), where n is the length of the string as we traverse the string a constant number of times. Space Complexity: O(1), aside from the result array, as the character count is constant with respect to the input size due to the alphabet limited to lowercase English letters.

Greedy Segment Selection

Time Complexity: O(n log n) due to sorting required on possible intervals. Space Complexity: O(n) due to interval and result storage.

Complexity analysis

ApproachTimeSpaceWhen to Use
Interval MergingO(n)O(1)When you want to explicitly construct all valid character intervals and reason about overlapping ranges.
Greedy Segment SelectionO(n)O(1)Best general solution. Efficient single-pass greedy choice that maximizes substring count.

Frequently asked questions

Is Maximum Number of Non-Overlapping Substrings easy or hard?

Maximum Number of Non-Overlapping Substrings is classified as a Hard problem on LeetCode. The difficulty comes from combining interval construction with greedy selection while ensuring every character in a substring is fully contained within it.

Maximum Number of Non-Overlapping Substrings Python/Java solution

Both Python and Java implementations follow the same logic: compute first and last indices, build valid intervals by expanding boundaries, and greedily select non-overlapping segments. The algorithm runs in O(n) time and uses constant extra space because the alphabet size is fixed.

How to solve Maximum Number of Non-Overlapping Substrings in O(n)?

Compute the first and last index of every character. For each index that matches a character's first occurrence, attempt to expand a substring until it includes the last occurrence of all characters inside it. If expansion stays valid, add the segment and greedily keep the one with the smallest ending index when overlaps occur. This linear scan produces the optimal set of substrings.

What is the best approach for Maximum Number of Non-Overlapping Substrings?

The greedy segment selection approach is the most efficient and commonly used solution. It first computes the first and last occurrence of each character, then builds minimal valid substrings and greedily keeps the ones with the smallest right boundary. This ensures the maximum number of non-overlapping substrings while keeping total length minimal. The overall complexity is O(n) time with O(1) extra space.

Is Maximum Number of Non-Overlapping Substrings asked at Google/Amazon/Meta?

Substring segmentation and greedy interval problems frequently appear in interviews at companies like Google, Amazon, and Meta. While the exact problem may vary, the pattern of computing character ranges and applying greedy interval selection is a common interview topic.

What data structure is used in Maximum Number of Non-Overlapping Substrings?

The solution mainly uses arrays or hash maps to store the first and last occurrence of each character. These structures allow constant-time lookups while expanding intervals. The algorithm also relies on greedy interval reasoning rather than complex data structures.

What is the time complexity of Maximum Number of Non-Overlapping Substrings?

The optimal solution runs in O(n) time where n is the length of the string. You first compute first and last occurrences of each character in O(n), then scan the string again to build and select valid substrings. Since the alphabet size is fixed (26 lowercase letters), space complexity remains O(1).

Comments

Now write it yourselfClose this page and solve Maximum Number of Non-Overlapping Substrings in the editor, without looking.
Practise Maximum Number of Non-Overlapping Substrings