#2781
Length of the Longest Valid Substring
HardArrayHash TableStringSliding WindowHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a sliding window approach allows us to efficiently find the longest valid substring without generating all possible substrings. This method expands and contracts the window based on the presence of forbidden substrings.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (start and end) and a set for forbidden substrings.
- 2Step 2: Expand the end pointer to include characters until a forbidden substring is found.
- 3Step 3: If a forbidden substring is found, move the start pointer to exclude characters until the substring is no longer present.
- 4Step 4: Keep track of the maximum length of valid substrings during the process.
solution.py12 lines
1def longestValidSubstring(word, forbidden):
2 forbidden_set = set(forbidden)
3 max_length = 0
4 start = 0
5 for end in range(len(word)):
6 for length in range(1, 11): # Check substrings of length 1 to 10
7 if end - length + 1 >= start:
8 substring = word[end - length + 1:end + 1]
9 if substring in forbidden_set:
10 start = end - length + 2 # Move start past the forbidden substring
11 max_length = max(max_length, end - start + 1)
12 return max_lengthℹ
Complexity note: The time complexity is O(n) because we traverse the string once with the end pointer and potentially check substrings of limited length (up to 10). The space complexity is O(n) due to the storage of the forbidden substrings in a set.
- 1Understanding forbidden substrings is crucial for identifying valid substrings.
- 2Using a sliding window can significantly reduce the time complexity compared to brute force.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.