Length of the Longest Valid Substring Problem
Description
LeetCode Problem 2781.
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 <= 10^5wordconsists only of lowercase English letters.1 <= forbidden.length <= 10^51 <= forbidden[i].length <= 10forbidden[i]consists only of lowercase English letters.
Solution
Approach: Sliding Window + Hash Set
Forbidden strings are at most 10 characters long, so a forbidden substring ending at position j can only start within the last 10 positions. Keep the left end i of the current window. For each right end j, check the substrings word[k..j] for k from j down to max(j - 9, i). If one is in the forbidden set, the window must start right after k, so set i = k + 1 and stop. Shrinking only ever moves i to the right, and checking the shortest suffixes first is enough because any longer hit would be found when its own end was processed. Track the largest window j - i + 1.
Complexity: O(n * L^2) time and O(m * L) space, where n is the length of word, L = 10 is the maximum forbidden length and m is the number of forbidden strings.
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