Maximum Length Substring With Two Occurrences - Problem
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
A substring is a contiguous sequence of characters within a string.
Input & Output
Example 1 — Basic Case
$
Input:
s = "bcbbbcba"
›
Output:
4
💡 Note:
The optimal substring is "bcbb" with b appearing 2 times and c appearing 1 time, giving length 4
Example 2 — All Same Character
$
Input:
s = "aaaa"
›
Output:
2
💡 Note:
Since we can have at most 2 occurrences of each character, the longest valid substring is "aa" with length 2
Example 3 — All Different Characters
$
Input:
s = "abcde"
›
Output:
5
💡 Note:
All characters are different, so the entire string is valid with length 5
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code