Problem Description
Given a string word and an array forbidden, determine the length of the longest contiguous substring of word that does not contain any substring from forbidden.
Key Insights
- Use a sliding window approach to efficiently check for valid substrings.
- Since every forbidden word has length at most 10, only the last 10 characters need to be checked when expanding the window.
- Utilize a hash set for O(1) lookup of forbidden substrings.
- Adjust the left boundary of the window when a forbidden substring is found within the current window.
Space and Time Complexity
Time Complexity: O(n * L), where n is the length of word and L is the maximum length (up to 10) of a forbidden word. Space Complexity: O(m), where m is the number of forbidden words stored in the hash set.
Solution
We apply a sliding window algorithm where we iterate through the string using a right pointer to extend the window. For each new character, only the last L characters (L = min(10, current window length)) are checked against the forbidden set. If any such substring is found in the forbidden set, the left pointer is moved ahead to exclude the forbidden substring from the current window. This ensures that the window always represents a valid substring. The maximum length encountered while sliding through the string is recorded and returned.