← All solutions

Maximum Length Substring With Two Occurrences

Easy
leetcode· Java· 2026-08-14Problem link ↗
Hash TableStringSliding Window

Runtime

1 ms

Beats 100%

Memory

43.4 MB

Beats 79.53%

Problem

Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.

 

Example 1:

Input: s = "bcbbbcba"

Output: 4

Explanation:

The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba".

Example 2:

Input: s = "aaaa"

Output: 2

Explanation:

The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa".

 

Constraints:

  • 2 <= s.length <= 100
  • s consists only of lowercase English letters.

Solution

Java
import java.util.*;

class Solution {
    public int maximumLengthSubstring(String s) {
        int[] count = new int[26];
        int left = 0;
        int maxLen = 0;
        int n = s.length();
        for (int right = 0; right < n; right++) {
            int charIdx = s.charAt(right) - 'a';
            count[charIdx]++;
            while (count[charIdx] > 2) {
                count[s.charAt(left) - 'a']--;
                left++;
            }
            maxLen = Math.max(maxLen, right - left + 1);
        }
        return maxLen;
    }
}