Find the longest substring in which no character appears more than twice.
Given a string , return the maximum length of a contiguous substring such that every distinct character inside that substring appears at most 2 times.
You may choose any substring of , but it must be contiguous. The answer is the length of the longest valid substring.
This problem is well-suited to a sliding window approach where you expand the window, track character frequencies, and shrink it whenever a character exceeds the allowed occurrence limit.
Input Format
- A single string .
- The string may contain lowercase letters, uppercase letters, digits, or other printable characters unless otherwise specified by the platform.
Output Format
- Return one integer: the maximum length of a substring where each character appears at most 2 times.
Constraints
- is a reasonable expected scale for this type of problem.
- Time complexity should ideally be linear or near-linear.
- Use extra space where is the number of distinct characters in the current window.
Example 1
Input
s = "bcbbbcba"
Output
5
Explanation
The longest valid substring is "cbbbc"? Let's check counts: c=2? Actually in "cbbbc" b appears 3 times, so invalid. A valid longest substring is "bcbbc" with b=3, invalid as well. One valid maximum substring is "bbbcba"? b appears 3 times. A correct longest valid substring is "cbbb"? b appears 3 times. For an illustrative example, use a string where the longest substring length is 5: s = "aabccdbb" gives "aabcc" with a=2, b=1, c=2.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.