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.
Given a string s of length n and an integer k, determine whether it is possible to select k disjoint special substrings.
A special substring is a substring where:
s.Note that all k substrings must be disjoint, meaning they cannot overlap.
Return true if it is possible to select k such disjoint special substrings; otherwise, return false.
Example 1:
Input: s = "abcdbaefab", k = 2
Output: true
Explanation:
"cd" and "ef"."cd" contains the characters 'c' and 'd', which do not appear elsewhere in s."ef" contains the characters 'e' and 'f', which do not appear elsewhere in s.Example 2:
Input: s = "cdefdc", k = 3
Output: false
Explanation:
There can be at most 2 disjoint special substrings: "e" and "f". Since k = 3, the output is false.
Example 3:
Input: s = "abeabe", k = 0
Output: true
Constraints:
2 <= n == s.length <= 5 * 1040 <= k <= 26s consists only of lowercase English letters.Problem summary: Given a string s of length n and an integer k, determine whether it is possible to select k disjoint special substrings. A special substring is a substring where: Any character present inside the substring should not appear outside it in the string. The substring is not the entire string s. Note that all k substrings must be disjoint, meaning they cannot overlap. Return true if it is possible to select k such disjoint special substrings; otherwise, return false.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Dynamic Programming · Greedy
"abcdbaefab" 2
"cdefdc" 3
"abeabe" 0
find-longest-self-contained-substring)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
class Solution {
public boolean maxSubstringLength(String s, int k) {
final int n = s.length();
int[] first = new int[26];
int[] last = new int[26];
// dp[i] := the maximum disjoint special substrings for the first i letters
int[] dp = new int[n + 1];
List<Character> seenOrder = new ArrayList<>();
Arrays.fill(first, n);
Arrays.fill(last, -1);
for (int i = 0; i < n; ++i) {
final char c = s.charAt(i);
final int a = c - 'a';
if (first[a] == n) {
first[a] = i;
seenOrder.add(c);
}
last[a] = i;
}
for (final char c : seenOrder) {
final int a = c - 'a';
for (int j = first[a]; j < last[a]; ++j) {
final int b = s.charAt(j) - 'a';
first[a] = Math.min(first[a], first[b]);
last[a] = Math.max(last[a], last[b]);
}
}
for (int i = 0; i < n; i++) {
final char c = s.charAt(i);
final int a = c - 'a';
if (last[a] != i || (first[a] == 0 && i == n - 1))
dp[i + 1] = dp[i];
else // Start a new special substring.
dp[i + 1] = Math.max(dp[i], 1 + dp[first[a]]);
}
return dp[n] >= k;
}
}
// Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
package main
import (
"slices"
"sort"
)
// https://space.bilibili.com/206214
func maxSubstringLength(s string, k int) bool {
if k == 0 { // 提前返回
return true
}
// 记录每种字母的出现位置
pos := [26][]int{}
for i, b := range s {
b -= 'a'
pos[b] = append(pos[b], i)
}
// 构建有向图
g := [26][]int{}
for i, p := range pos {
if p == nil {
continue
}
l, r := p[0], p[len(p)-1]
for j, q := range pos {
if j == i {
continue
}
k := sort.SearchInts(q, l)
// [l,r] 包含第 j 个小写字母
if k < len(q) && q[k] <= r {
g[i] = append(g[i], j)
}
}
}
// 遍历有向图
vis := [26]bool{}
var l, r int
var dfs func(int)
dfs = func(x int) {
vis[x] = true
p := pos[x]
l = min(l, p[0]) // 合并区间
r = max(r, p[len(p)-1])
for _, y := range g[x] {
if !vis[y] {
dfs(y)
}
}
}
intervals := [][2]int{}
for i, p := range pos {
if p == nil {
continue
}
// 如果要包含第 i 个小写字母,最终得到的区间是什么?
vis = [26]bool{}
l, r = len(s), 0
dfs(i)
// 不能选整个 s,即区间 [0,n-1]
if l > 0 || r < len(s)-1 {
intervals = append(intervals, [2]int{l, r})
}
}
return maxNonoverlapIntervals(intervals) >= k
}
// 435. 无重叠区间
// 直接计算最多能选多少个区间
func maxNonoverlapIntervals(intervals [][2]int) (ans int) {
slices.SortFunc(intervals, func(a, b [2]int) int { return a[1] - b[1] })
preR := 0
for _, p := range intervals {
if p[0] >= preR {
ans++
preR = p[1]
}
}
return
}
# Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
class Solution:
def maxSubstringLength(self, s: str, k: int) -> bool:
n = len(s)
first = [n] * 26
last = [-1] * 26
# dp[i] := the maximum disjoint special substrings for the first i letters
dp = [0] * (n + 1)
seenOrder = []
for i, c in enumerate(s):
a = ord(c) - ord('a')
if first[a] == n:
first[a] = i
seenOrder.append(c)
last[a] = i
for c in seenOrder:
a = ord(c) - ord('a')
for j in range(first[a], last[a]):
b = ord(s[j]) - ord('a')
first[a] = min(first[a], first[b])
last[a] = max(last[a], last[b])
for i, c in enumerate(s):
a = ord(c) - ord('a')
if last[a] != i or (first[a] == 0 and i == n - 1):
dp[i + 1] = dp[i]
else: # Start a new special substring.
dp[i + 1] = max(dp[i], 1 + dp[first[a]])
return dp[n] >= k
// Accepted solution for LeetCode #3458: Select K Disjoint Special 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 #3458: Select K Disjoint Special Substrings
// class Solution {
// public boolean maxSubstringLength(String s, int k) {
// final int n = s.length();
// int[] first = new int[26];
// int[] last = new int[26];
// // dp[i] := the maximum disjoint special substrings for the first i letters
// int[] dp = new int[n + 1];
// List<Character> seenOrder = new ArrayList<>();
//
// Arrays.fill(first, n);
// Arrays.fill(last, -1);
//
// for (int i = 0; i < n; ++i) {
// final char c = s.charAt(i);
// final int a = c - 'a';
// if (first[a] == n) {
// first[a] = i;
// seenOrder.add(c);
// }
// last[a] = i;
// }
//
// for (final char c : seenOrder) {
// final int a = c - 'a';
// for (int j = first[a]; j < last[a]; ++j) {
// final int b = s.charAt(j) - 'a';
// first[a] = Math.min(first[a], first[b]);
// last[a] = Math.max(last[a], last[b]);
// }
// }
//
// for (int i = 0; i < n; i++) {
// final char c = s.charAt(i);
// final int a = c - 'a';
// if (last[a] != i || (first[a] == 0 && i == n - 1))
// dp[i + 1] = dp[i];
// else // Start a new special substring.
// dp[i + 1] = Math.max(dp[i], 1 + dp[first[a]]);
// }
//
// return dp[n] >= k;
// }
// }
// Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3458: Select K Disjoint Special Substrings
// class Solution {
// public boolean maxSubstringLength(String s, int k) {
// final int n = s.length();
// int[] first = new int[26];
// int[] last = new int[26];
// // dp[i] := the maximum disjoint special substrings for the first i letters
// int[] dp = new int[n + 1];
// List<Character> seenOrder = new ArrayList<>();
//
// Arrays.fill(first, n);
// Arrays.fill(last, -1);
//
// for (int i = 0; i < n; ++i) {
// final char c = s.charAt(i);
// final int a = c - 'a';
// if (first[a] == n) {
// first[a] = i;
// seenOrder.add(c);
// }
// last[a] = i;
// }
//
// for (final char c : seenOrder) {
// final int a = c - 'a';
// for (int j = first[a]; j < last[a]; ++j) {
// final int b = s.charAt(j) - 'a';
// first[a] = Math.min(first[a], first[b]);
// last[a] = Math.max(last[a], last[b]);
// }
// }
//
// for (int i = 0; i < n; i++) {
// final char c = s.charAt(i);
// final int a = c - 'a';
// if (last[a] != i || (first[a] == 0 && i == n - 1))
// dp[i + 1] = dp[i];
// else // Start a new special substring.
// dp[i + 1] = Math.max(dp[i], 1 + dp[first[a]]);
// }
//
// return dp[n] >= k;
// }
// }
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.