Maximum Length Substring With Two Occurrences Problem
#3090
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3090.
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Example 1:
Input: s = "bcbbbcba"
Output: 4
Explanation:
The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".
Example 2:
Input: s = "aaaa"
Output: 2
Explanation:
The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".
Constraints:
2 <= s.length <= 100sconsists only of lowercase English letters.
Solution
Approach: Two Pointers
Keep a sliding window [l, r] and the count of each letter inside it. Add s[r]; while its count exceeds 2, move l to the right, removing letters. After each step the window is valid, so update the answer with r - l + 1.
Complexity: O(n) time, O(26) space.
from collections import defaultdict
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
ans = l = 0
cnt = defaultdict(int)
for r, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 2:
cnt[s[l]] -= 1
l += 1
ans = max(ans, r - l + 1)
return ans