Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a string word and an array of strings forbidden.
A string is called valid if none of its substrings are present in forbidden.
Return the length of the longest valid substring of the string word.
A substring is a contiguous sequence of characters in a string, possibly empty.
Example 1:
Input: word = "cbaaaabc", forbidden = ["aaa","cb"] Output: 4 Explanation: There are 11 valid substrings in word: "c", "b", "a", "ba", "aa", "bc", "baa", "aab", "ab", "abc" and "aabc". The length of the longest valid substring is 4. It can be shown that all other substrings contain either "aaa" or "cb" as a substring.
Example 2:
Input: word = "leetcode", forbidden = ["de","le","e"] Output: 4 Explanation: There are 11 valid substrings in word: "l", "t", "c", "o", "d", "tc", "co", "od", "tco", "cod", and "tcod". The length of the longest valid substring is 4. It can be shown that all other substrings contain either "de", "le", or "e" as a substring.
Constraints:
1 <= word.length <= 105word consists only of lowercase English letters.1 <= forbidden.length <= 1051 <= forbidden[i].length <= 10forbidden[i] consists only of lowercase English letters.Problem summary: You are given a string word and an array of strings forbidden. A string is called valid if none of its substrings are present in forbidden. Return the length of the longest valid substring of the string word. A substring is a contiguous sequence of characters in a string, possibly empty.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Sliding Window
"cbaaaabc" ["aaa","cb"]
"leetcode" ["de","le","e"]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2781: Length of the Longest Valid Substring
class Solution {
public int longestValidSubstring(String word, List<String> forbidden) {
var s = new HashSet<>(forbidden);
int ans = 0, n = word.length();
for (int i = 0, j = 0; j < n; ++j) {
for (int k = j; k > Math.max(j - 10, i - 1); --k) {
if (s.contains(word.substring(k, j + 1))) {
i = k + 1;
break;
}
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
}
// Accepted solution for LeetCode #2781: Length of the Longest Valid Substring
func longestValidSubstring(word string, forbidden []string) (ans int) {
s := map[string]bool{}
for _, x := range forbidden {
s[x] = true
}
n := len(word)
for i, j := 0, 0; j < n; j++ {
for k := j; k > max(j-10, i-1); k-- {
if s[word[k:j+1]] {
i = k + 1
break
}
}
ans = max(ans, j-i+1)
}
return
}
# Accepted solution for LeetCode #2781: Length of the Longest Valid Substring
class Solution:
def longestValidSubstring(self, word: str, forbidden: List[str]) -> int:
s = set(forbidden)
ans = i = 0
for j in range(len(word)):
for k in range(j, max(j - 10, i - 1), -1):
if word[k : j + 1] in s:
i = k + 1
break
ans = max(ans, j - i + 1)
return ans
// Accepted solution for LeetCode #2781: Length of the Longest Valid Substring
// 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 #2781: Length of the Longest Valid Substring
// class Solution {
// public int longestValidSubstring(String word, List<String> forbidden) {
// var s = new HashSet<>(forbidden);
// int ans = 0, n = word.length();
// for (int i = 0, j = 0; j < n; ++j) {
// for (int k = j; k > Math.max(j - 10, i - 1); --k) {
// if (s.contains(word.substring(k, j + 1))) {
// i = k + 1;
// break;
// }
// }
// ans = Math.max(ans, j - i + 1);
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2781: Length of the Longest Valid Substring
function longestValidSubstring(word: string, forbidden: string[]): number {
const s: Set<string> = new Set(forbidden);
const n = word.length;
let ans = 0;
for (let i = 0, j = 0; j < n; ++j) {
for (let k = j; k > Math.max(j - 10, i - 1); --k) {
if (s.has(word.substring(k, j + 1))) {
i = k + 1;
break;
}
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
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: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.