Maximum Number of Non-Overlapping Substrings — LeetCode 1520 Python Solution

HardGreedyString
Problem
#1520
Pattern
Greedy
Reading time
2 min

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: 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. A substring that contains a certain character c must also contain all occurrences of c.

Example

Input
s = "adefaddaccc"
Output
["e","f","ccc"]
Explanation
The following are all the possible substrings that meet the conditions:

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1520. Maximum Number of Non-Overlapping Substrings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1520. Maximum Number of Non-Overlapping Substrings?
LeetCode 1520. Maximum Number of Non-Overlapping Substrings is rated Hard on LeetCode.
What topics does LeetCode 1520. Maximum Number of Non-Overlapping Substrings cover?
LeetCode 1520. Maximum Number of Non-Overlapping Substrings is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview