Longest Substring with At Most Two Distinct Characters, explained
Longest Substring with At Most Two Distinct Characters can be solved in one pass with constant memory. Walk the string while remembering the two kinds of character in the current stretch and how long the most recent run of the latest character is; when a third kind appears, the new stretch is that trailing run plus the new character. Keep the longest length seen. That is O(n) time and O(1) space, and the general sliding window for any k gives the same answer.
By Evin JohnPublished 7 min read
The task
Given a string, find the length of the longest substring, a run of consecutive characters, that contains at most two different characters. A substring made of a single repeated character counts, and so does the empty string when the input is empty. The question is a special case of the at-most-k version with k fixed at 2, and interviewers often ask it first, then generalize.
| String | Answer | A longest stretch |
|---|---|---|
cabbage | 4 | abba |
abaccc | 4 | accc |
aabbaacc | 6 | aabbaa |
tomato | 2 | to, om, ma and others |
zzzz | 4 | zzzz |
| empty string | 0 | nothing |
Why it gets asked
It is short enough for a phone screen and has a satisfying insight. Most candidates reach a correct sliding window with a dictionary. The follow-up "can you do it without a map?" separates people who memorized a template from people who understand what the window actually contains. The array version, where each value is a type of fruit and you may carry only two types, is the same problem with integers instead of letters.
Brute force
def two_kinds_brute(s):
longest = 0
for i in range(len(s)):
seen = []
j = i
while j < len(s) and (s[j] in seen or len(seen) < 2):
if s[j] not in seen:
seen.append(s[j])
j += 1
longest = max(longest, j - i)
return longestThe key observation
Suppose the current stretch holds kinds x and y, and the last character read was y. A new character z arrives that is neither. Any valid stretch ending at z can hold only one of the old kinds, and it must be the kind directly before z, which is y. It can reach back exactly as far as the unbroken run of y that ends just before z. So the new stretch length is that run length plus one, and nothing else about the past matters. That is why you never need a map of counts.
- Track two kinds
prev_kindandlast_kind, wherelast_kindis the character read most recently. - Track two lengths
curis the length of the valid stretch ending here;runis the length of the trailing run oflast_kind. - On each characterIf it is one of the two kinds,
curgrows by one; otherwisecurbecomesrun + 1. Then updaterun: add one if the character equalslast_kind, else reset to 1 and shift the kinds. - Keep the maximumCompare
curwith the best after every character.
def two_kinds_longest(s):
best = cur = run = 0
prev_kind = last_kind = None
for ch in s:
if ch == last_kind or ch == prev_kind:
cur += 1
else:
cur = run + 1 # trailing run of last_kind, plus ch
if ch == last_kind:
run += 1
else:
run = 1
prev_kind, last_kind = last_kind, ch
best = max(best, cur)
return bestfunction twoKindsLongest(s) {
let best = 0, cur = 0, run = 0;
let prevKind = null, lastKind = null;
for (const ch of s) {
if (ch === lastKind || ch === prevKind) cur += 1;
else cur = run + 1;
if (ch === lastKind) {
run += 1;
} else {
run = 1;
prevKind = lastKind;
lastKind = ch;
}
best = Math.max(best, cur);
}
return best;
}Trace abaccc. After a, b, a the stretch is aba, cur is 3, and the trailing run of a is 1. Then c arrives: cur becomes 1 + 1 = 2 (ac), kinds shift to a and c. Two more c characters make cur 4. The best is 4. Note that the JavaScript loop uses for...of, which walks whole code points, so an emoji counts as one character; the Python loop does the same.
Another way: remember last positions
If you prefer an explicit window, store the latest index of each kind in a small dictionary. When it grows to three entries, the kind with the smallest latest index is the one to drop, and the window starts just after that index. The dictionary never holds more than three keys, so finding the smallest is constant work. This version generalizes directly to k kinds, though for large k you would want an ordered structure instead of scanning.
def two_kinds_positions(s):
latest = {}
start = longest = 0
for i, ch in enumerate(s):
latest[ch] = i
if len(latest) == 3:
drop = min(latest, key=latest.get)
start = latest.pop(drop) + 1
longest = max(longest, i - start + 1)
return longestComplexity
| Approach | Time | Extra space |
|---|---|---|
| Every start, walk right | O(n²) | O(1) |
| Latest positions, at most three keys | O(n) | O(1) |
| Two kinds and the trailing run | O(n) | O(1), five variables |
| General at-most-k window with counts | O(n) | O(k), here O(1) |
Edge cases
- Empty string and a single character.
- One kind only, such as
zzzz: the answer is the full length. - Alternating two kinds, where nothing ever resets.
- A third kind right after a long run, such as
abbbbc, where the new stretch keeps the whole run ofb. - A third kind right after a single character, such as
abac, where only one old character stays. - The initial
Noneornullvalues must never equal a real character; with strings they cannot.
Mistakes
- Resetting
curto 2 when a third kind appears. The new stretch keeps the whole trailing run, not one character. - Updating
runbefore using it to computecur. - Shifting the kinds on every character instead of only when the kind changes.
- Forgetting that the best can come from the final stretch, so the maximum must be taken inside the loop.
- In the positions version, dropping the kind with the earliest first appearance rather than the earliest latest appearance.
How to talk through it
Fictional example
- Interviewer
- Your dictionary window works. Can you do it without the dictionary?
- Candidate
- When a third kind shows up, the only old character that can stay is the one right before it, and only its unbroken run. So I just need to know the last two kinds and how long the current run of the latest one is.
- Candidate
- On a new kind, the stretch becomes run plus one. On a known kind, it grows by one. I update the run after that. It is still one pass, and memory is five variables.
Related problems
For any k, use the count-map window on Longest Substring with At Most K Distinct Characters. If you instead need to count how many subarrays have exactly two kinds, the at-most trick on Subarrays with K Different Integers is the tool. A sorted-array counting problem with a similar batch step is 3Sum Smaller.
Using Natively while you prepare
During practice on a Mac or Windows PC, Natively can capture a short problem like this from your screen and propose code, so you can test whether its version and yours agree on traps like abbbbc. It keeps a transcript of the mock interview, which helps you check that you explained the trailing-run idea clearly rather than just writing it. See how an AI interview assistant fits into practice.
Questions people ask
How do you solve longest substring with at most two distinct characters?
Scan once, remembering the last two kinds and the length of the trailing run of the latest one. On a third kind, the new stretch is that run plus one; otherwise it grows by one.
Can it be done without a hash map?
Yes. Five variables are enough: two characters, the current stretch length, the trailing run length and the best length, giving O(1) memory.
Why does only the trailing run survive a third character?
A valid stretch ending at the new character can keep only one old kind, the one directly before it, and only its unbroken run.
Is this the same as the fruit into baskets problem?
Yes, the same idea over an array of types: the longest stretch with at most two different values.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
