Skip to content

3090. Maximum Length Substring With Two Occurrences

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:

class Solution {
    public int maximumLengthSubstring(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();


        int slow = 0;
        char chTwo;
        int result = 0;
        for (int fast = 0; fast < s.length(); fast++){
            char ch = s.charAt(fast);
            if (!map.containsKey(ch)){
                map.put(ch, 1);
            }else{
                // contains
                map.put(ch, map.get(ch) + 1);
                int curNum = map.get(ch);

                if (curNum == 2){
                    chTwo = ch;
                }

                if (curNum == 3){
                    if (s.charAt(slow) == ch){
                        slow++;
                        curNum--;
                        map.put(ch, map.get(ch) - 1);
                    }else{
                        while(s.charAt(slow) != ch){
                            map.put(s.charAt(slow), map.get(s.charAt(slow)) - 1);
                            slow++;
                        }
                        map.put(ch, map.get(ch) -1);
                        slow++;
                    }
                }
            }

            result = Math.max(fast - slow + 1, result);

        }

        return result;
    }
}

// TC:O(n)
// SC:O(n)