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 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
๐Ÿ›ก๏ธ Security Document ScannerFinding longest safe section without forbidden contentDocument: "confidential-data-analysis-report"๐Ÿšซ Blacklist["data", "confidential"]๐Ÿ“ Current Scan Zone"analysis-report" โœ“๐ŸŽฏ Longest Safe Section: "analysis-report" (length: 15)!Skip forbidden contentโœ“Safe content
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
38.5K Views
Medium-High Frequency
~25 min Avg. Time
1.2K 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