Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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:
s[i..j] and s[x..y], either j < x or i > y is true.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 <= 105s contains only lowercase English letters.Problem summary: 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. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Greedy
"adefaddaccc"
"abbaccd"
maximum-number-of-non-overlapping-palindrome-substrings)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// Auto-generated Java example from py.
class Solution {
public void exampleSolution() {
}
}
// Reference (py):
// # Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// # Time: O(n)
// # space: O(1)
//
// class Solution(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// result = [""]
// right = float("inf")
// for left, c in enumerate(s):
// if left != first[ord(c)-ord('a')]:
// continue
// new_right = find_right_from_left(s, first, last, left)
// if new_right == -1:
// continue
// if left > right:
// result.append("")
// right = new_right
// result[-1] = s[left:right+1]
// return result
//
//
// # Time: O(n)
// # space: O(1)
// class Solution2(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// intervals = []
// for c in xrange(len(first)):
// if first[c] == float("inf"):
// continue
// left, right = first[c], find_right_from_left(s, first, last, first[c])
// if right != -1:
// intervals.append((right, left))
// intervals.sort() # Time: O(26log26)
// result, prev = [], -1
// for right, left in intervals:
// if left <= prev:
// continue
// result.append(s[left:right+1])
// prev = right
// return result
// Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// Auto-generated Go example from py.
func exampleSolution() {
}
// Reference (py):
// # Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// # Time: O(n)
// # space: O(1)
//
// class Solution(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// result = [""]
// right = float("inf")
// for left, c in enumerate(s):
// if left != first[ord(c)-ord('a')]:
// continue
// new_right = find_right_from_left(s, first, last, left)
// if new_right == -1:
// continue
// if left > right:
// result.append("")
// right = new_right
// result[-1] = s[left:right+1]
// return result
//
//
// # Time: O(n)
// # space: O(1)
// class Solution2(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// intervals = []
// for c in xrange(len(first)):
// if first[c] == float("inf"):
// continue
// left, right = first[c], find_right_from_left(s, first, last, first[c])
// if right != -1:
// intervals.append((right, left))
// intervals.sort() # Time: O(26log26)
// result, prev = [], -1
// for right, left in intervals:
// if left <= prev:
// continue
// result.append(s[left:right+1])
// prev = right
// return result
# Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
# Time: O(n)
# space: O(1)
class Solution(object):
def maxNumOfSubstrings(self, s):
"""
:type s: str
:rtype: List[str]
"""
def find_right_from_left(s, first, last, left):
right, i = last[ord(s[left])-ord('a')], left
while i <= right:
if first[ord(s[i])-ord('a')] < left:
return -1
right = max(right, last[ord(s[i])-ord('a')])
i += 1
return right
first, last = [float("inf")]*26, [float("-inf")]*26
for i, c in enumerate(s):
first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
result = [""]
right = float("inf")
for left, c in enumerate(s):
if left != first[ord(c)-ord('a')]:
continue
new_right = find_right_from_left(s, first, last, left)
if new_right == -1:
continue
if left > right:
result.append("")
right = new_right
result[-1] = s[left:right+1]
return result
# Time: O(n)
# space: O(1)
class Solution2(object):
def maxNumOfSubstrings(self, s):
"""
:type s: str
:rtype: List[str]
"""
def find_right_from_left(s, first, last, left):
right, i = last[ord(s[left])-ord('a')], left
while i <= right:
if first[ord(s[i])-ord('a')] < left:
return -1
right = max(right, last[ord(s[i])-ord('a')])
i += 1
return right
first, last = [float("inf")]*26, [float("-inf")]*26
for i, c in enumerate(s):
first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
intervals = []
for c in xrange(len(first)):
if first[c] == float("inf"):
continue
left, right = first[c], find_right_from_left(s, first, last, first[c])
if right != -1:
intervals.append((right, left))
intervals.sort() # Time: O(26log26)
result, prev = [], -1
for right, left in intervals:
if left <= prev:
continue
result.append(s[left:right+1])
prev = right
return result
// Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
struct Solution;
impl Solution {
fn max_num_of_substrings(s: String) -> Vec<String> {
let n = s.len();
let s: Vec<u8> = s.bytes().collect();
let mut l = vec![std::usize::MAX; 26];
let mut r = vec![std::usize::MIN; 26];
for i in 0..n {
let j = (s[i] - b'a') as usize;
l[j] = l[j].min(i);
r[j] = r[j].max(i);
}
let mut res = vec![];
let mut end = 0;
for i in 0..n {
let j = (s[i] - b'a') as usize;
if i == l[j] {
if let Some(new_end) = Self::check(i, &l, &r, &s) {
if new_end < end {
res.pop();
}
res.push(s[i..new_end].iter().map(|&b| b as char).collect::<String>());
end = new_end;
}
}
}
res
}
fn check(start: usize, l: &[usize], r: &[usize], s: &[u8]) -> Option<usize> {
let mut end = r[(s[start] - b'a') as usize] + 1;
let mut i = start;
while i < end {
if l[(s[i] - b'a') as usize] < start {
return None;
} else {
end = end.max(r[(s[i] - b'a') as usize] + 1);
}
i += 1;
}
Some(end)
}
}
#[test]
fn test() {
let s = "adefaddaccc".to_string();
let res = vec_string!["e", "f", "ccc"];
assert_eq!(Solution::max_num_of_substrings(s), res);
}
// Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// Auto-generated TypeScript example from py.
function exampleSolution(): void {
}
// Reference (py):
// # Accepted solution for LeetCode #1520: Maximum Number of Non-Overlapping Substrings
// # Time: O(n)
// # space: O(1)
//
// class Solution(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// result = [""]
// right = float("inf")
// for left, c in enumerate(s):
// if left != first[ord(c)-ord('a')]:
// continue
// new_right = find_right_from_left(s, first, last, left)
// if new_right == -1:
// continue
// if left > right:
// result.append("")
// right = new_right
// result[-1] = s[left:right+1]
// return result
//
//
// # Time: O(n)
// # space: O(1)
// class Solution2(object):
// def maxNumOfSubstrings(self, s):
// """
// :type s: str
// :rtype: List[str]
// """
// def find_right_from_left(s, first, last, left):
// right, i = last[ord(s[left])-ord('a')], left
// while i <= right:
// if first[ord(s[i])-ord('a')] < left:
// return -1
// right = max(right, last[ord(s[i])-ord('a')])
// i += 1
// return right
//
// first, last = [float("inf")]*26, [float("-inf")]*26
// for i, c in enumerate(s):
// first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
// last[ord(c)-ord('a')] = max(last[ord(c)-ord('a')], i)
// intervals = []
// for c in xrange(len(first)):
// if first[c] == float("inf"):
// continue
// left, right = first[c], find_right_from_left(s, first, last, first[c])
// if right != -1:
// intervals.append((right, left))
// intervals.sort() # Time: O(26log26)
// result, prev = [], -1
// for right, left in intervals:
// if left <= prev:
// continue
// result.append(s[left:right+1])
// prev = right
// return result
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.