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
Length of the Longest Valid Substring INPUT word = "cbaaaabc" c 0 b 1 a 2 a 3 a 4 a 5 b 6 c 7 forbidden = ["aaa", "cb"] "aaa" "cb" Hash Set for O(1) Lookup {"aaa", "cb"} Quick forbidden check Sliding Window Approach left=0, right=0 to n-1 ALGORITHM STEPS 1 Build Hash Set Store forbidden strings for O(1) lookup 2 Sliding Window Expand right, check substrings ending at right 3 Check Forbidden Only check substrings up to max forbidden len 4 Shrink if Found Move left past the forbidden substring Valid Window Found: a a b c "aabc" at indices 4-7 maxLen = max(maxLen, right-left+1) FINAL RESULT Longest Valid Substring a a b c "aabc" (indices 4 to 7) Output: 4 [OK] Verified: - "aabc" has no "aaa" substring - "aabc" has no "cb" substring - Length 4 is maximum possible - "cbaaa" invalid (has "cb") No valid substring longer than 4 Key Insight: Using a Hash Set allows O(1) lookup for forbidden strings. The sliding window only needs to check substrings up to the maximum length of forbidden words (here: 3). When a forbidden substring is found, we shrink the window from left. Time: O(n * m * k) where m = max forbidden length, k = count. TutorialsPoint - Length of the Longest Valid Substring | Hash + Sliding Window Approach
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