Skip to main content
Back to problems
Leetcode
Medium
Strings
Hash Maps
Sliding Window
Google
Maximum Length Substring With Two Occurrences

Find the longest substring in which no character appears more than twice.

Acceptance 0%
Problem Statement

Given a string ss, 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 ss, 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 ss.
  • 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

  • 1≤∣s∣≤1051 \le |s| \le 10^5 is a reasonable expected scale for this type of problem.
  • Time complexity should ideally be linear or near-linear.
  • Use O(k)O(k) extra space where kk is the number of distinct characters in the current window.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.