#3090
Maximum Length Substring With Two Occurrences
EasyHash 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)
The optimal solution uses a sliding window approach to maintain a substring that contains at most two occurrences of each character. This is efficient because it avoids checking all possible substrings and instead expands and contracts the window based on character counts.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (left and right) and a hashmap to count character occurrences.
- 2Step 2: Expand the right pointer to include characters until the condition is violated (more than two occurrences of any character).
- 3Step 3: When the condition is violated, move the left pointer to reduce the count of characters until the condition is satisfied again.
- 4Step 4: Keep track of the maximum length of valid substrings during the process.
solution.py13 lines
1def maxLengthSubstring(s):
2 left = 0
3 count = {}
4 max_length = 0
5 for right in range(len(s)):
6 count[s[right]] = count.get(s[right], 0) + 1
7 while count[s[right]] > 2:
8 count[s[left]] -= 1
9 if count[s[left]] == 0:
10 del count[s[left]]
11 left += 1
12 max_length = max(max_length, right - left + 1)
13 return max_lengthℹ
Complexity note: The time complexity is O(n) because each character is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(n) due to the hashmap storing character counts.
- 1Using a sliding window allows us to efficiently manage the substring without generating all possible substrings.
- 2Maintaining a character count helps in quickly determining if the substring meets the condition.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.