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.
Move from brute-force thinking to an efficient approach using hash map strategy.
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 * 105word consists only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Dynamic Programming · Greedy
"abcdeafdef"
"bcdaaaab"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
class Solution {
public int maxSubstrings(String word) {
int ans = 0;
Map<Character, Integer> firstSeen = new HashMap<>();
for (int i = 0; i < word.length(); ++i) {
final char c = word.charAt(i);
if (!firstSeen.containsKey(c)) {
firstSeen.put(c, i);
} else if (i - firstSeen.get(c) + 1 >= 4) {
++ans;
firstSeen.clear();
}
}
return ans;
}
}
// Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
package main
// https://space.bilibili.com/206214
func maxSubstrings1(word string) (ans int) {
pos := [26]int{}
for i, b := range word {
b -= 'a'
if pos[b] == 0 {
pos[b] = i + 1
} else if i-pos[b] > 1 {
ans++
clear(pos[:])
}
}
return
}
func maxSubstrings(word string) (ans int) {
seen := 0
for i := 3; i < len(word); i++ {
seen |= 1 << (word[i-3] - 'a')
if seen>>(word[i]-'a')&1 > 0 { // 再次遇到 word[i]
ans++
seen = 0
i += 3
}
}
return
}
func maxSubstringsDP(word string) int {
pos := [26][]int{}
n := len(word)
f := make([]int, n+1)
for i, b := range word {
b -= 'a'
for len(pos[b]) > 1 && i-pos[b][1] > 2 {
pos[b] = pos[b][1:]
}
f[i+1] = f[i] // 不选 s[i]
if len(pos[b]) > 0 && i-pos[b][0] > 2 {
f[i+1] = max(f[i+1], f[pos[b][0]]+1) // 选 s[i]
}
pos[b] = append(pos[b], i)
}
return f[n]
}
# Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
class Solution:
def maxSubstrings(self, word: str) -> int:
ans = 0
firstSeen = {}
for i, c in enumerate(word):
if c not in firstSeen:
firstSeen[c] = i
elif i - firstSeen[c] + 1 >= 4:
ans += 1
firstSeen.clear()
return ans
// Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
// class Solution {
// public int maxSubstrings(String word) {
// int ans = 0;
// Map<Character, Integer> firstSeen = new HashMap<>();
//
// for (int i = 0; i < word.length(); ++i) {
// final char c = word.charAt(i);
// if (!firstSeen.containsKey(c)) {
// firstSeen.put(c, i);
// } else if (i - firstSeen.get(c) + 1 >= 4) {
// ++ans;
// firstSeen.clear();
// }
// }
//
// return ans;
// }
// }
// Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3557: Find Maximum Number of Non Intersecting Substrings
// class Solution {
// public int maxSubstrings(String word) {
// int ans = 0;
// Map<Character, Integer> firstSeen = new HashMap<>();
//
// for (int i = 0; i < word.length(); ++i) {
// final char c = word.charAt(i);
// if (!firstSeen.containsKey(c)) {
// firstSeen.put(c, i);
// } else if (i - firstSeen.get(c) + 1 >= 4) {
// ++ans;
// firstSeen.clear();
// }
// }
//
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
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: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
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.