Length of the Longest Valid Substring - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: word = "cbaaaabc", forbidden = ["aaa", "cb"]
Output: 4
💡 Note: Valid substrings include "c", "b", "a", "aa", "aaaa", "b", "c", "ba", "bc". The longest is "aaaa" with length 4. Substrings containing "aaa" or "cb" are invalid.
Example 2 — No Forbidden
$ Input: word = "leetcode", forbidden = []
Output: 8
💡 Note: Since no strings are forbidden, the entire string "leetcode" is valid with length 8.
Example 3 — All Invalid
$ Input: word = "aab", forbidden = ["a"]
Output: 1
💡 Note: Only valid substring is "b" since any substring containing "a" is forbidden. Maximum length is 1.

Constraints

  • 1 ≤ word.length ≤ 104
  • 0 ≤ forbidden.length ≤ 105
  • 1 ≤ forbidden[i].length ≤ 10
  • word and forbidden[i] consist of lowercase English letters.

Visualization

Tap to expand
Longest Valid Substring ProblemInput: word = "cbaaaabc", forbidden = ["aaa", "cb"]cbaaaabc"cb" - Forbidden"aaa" - Forbidden"aaaa" - Valid (length 4)Output: Maximum length = 4
Understanding the Visualization
1
Input
String 'cbaaaabc' with forbidden ['aaa', 'cb']
2
Process
Find all valid substrings avoiding forbidden ones
3
Output
Length 4 for longest valid substring 'aaaa'
Key Takeaway
🎯 Key Insight: Use sliding window to find maximum valid substring length while avoiding forbidden patterns
Asked in
Google 25 Amazon 18 Microsoft 15
34.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen