Length of the Longest Valid Substring - Problem
Find the longest valid substring in a given string where none of its substrings appear in a forbidden list.
You are given a string
Example: If
Goal: Return the length of the longest valid substring possible.
You are given a string
word and an array of strings forbidden. A substring is considered valid if none of its contiguous parts match any string in the forbidden array.Example: If
word = "cbaaaabc" and forbidden = ["aaa", "cb"], then the substring "aaab" is invalid because it contains "aaa", but "aa" would be valid.Goal: Return the length of the longest valid substring possible.
Input & Output
example_1.py โ Basic Case
$
Input:
word = "cbaaaabc", forbidden = ["aaa", "cb"]
โบ
Output:
4
๐ก Note:
The longest valid substring is "aaab" with length 4. It doesn't contain "aaa" or "cb" as substrings.
example_2.py โ No Forbidden Match
$
Input:
word = "leetcode", forbidden = ["de", "le", "e"]
โบ
Output:
4
๐ก Note:
The longest valid substring is "tcod" with length 4, as it doesn't contain any forbidden substrings.
example_3.py โ Edge Case
$
Input:
word = "a", forbidden = ["b"]
โบ
Output:
1
๐ก Note:
Since "a" doesn't contain the forbidden string "b", the entire string is valid with length 1.
Constraints
- 1 โค word.length โค 104
- word consists only of lowercase English letters
- 1 โค forbidden.length โค 104
- 1 โค forbidden[i].length โค 10
- forbidden[i] consists only of lowercase English letters
- All strings in forbidden are unique
Visualization
Tap to expand
Understanding the Visualization
1
Setup Scanner
Load forbidden phrases into memory for quick lookup
2
Scan Forward
Move through document expanding safe zone
3
Hit Forbidden
When sensitive content found, restart after the forbidden phrase begins
4
Track Maximum
Remember the longest safe section discovered
Key Takeaway
๐ฏ Key Insight: When we find a forbidden substring, we don't need to check overlapping substrings - we can jump directly past the start of the forbidden content!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code