Return the length of the longest substring of s containing at most two distinct
characters.
longestTwoCharSubstring(s)
Input format: a single string (may be empty).
"eceba" // → 3 ("ece")
"ccaabbb" // → 5 ("aabbb")
"abc" // → 2
"" // → 0
You want the longest substring using at most two distinct characters. Like "longest unique substring," checking every substring and counting distinct characters from scratch is O(n²) substrings, each costing up to O(n) — wasteful since neighboring windows share almost everything.
The thing that can go wrong is the distinct-character count exceeding two. Keep a running frequency map of characters in the window — the number of keys is exactly the distinct count, no rescanning needed.
The window becomes invalid the moment the map's key count reaches three. Remove characters from the left one at a time: decrement the leftmost's count, delete it if it hits zero, until at most two keys remain.
right forward, incrementing the new character's count.s[left]'s count, delete if zero, advance left.right reaches the end.Each character enters once and leaves at most once, so both pointers move forward monotonically — O(n) total instead of O(n²). Using a map instead of rescanning is what makes each step O(1) amortized. This is a small variation on the unique-substring pattern: tracking "how many distinct" instead of "any duplicate," shrinking whenever the count crosses a threshold.
def longest_two_char_substring(s):
count = {}
left = 0
best = 0
for right in range(len(s)):
count[s[right]] = count.get(s[right], 0) + 1
while len(count) > 2:
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
if right - left + 1 > best:
best = right - left + 1
return best
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.