Skip to content

159. Longest Substring with At Most Two Distinct Characters

Given a string s, return the length of the longest substring that contains at most two distinct characters**.

Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

Constraints:

  • 1 <= s.length <= 105
  • s consists of English letters.

Solution:

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

        int slow = 0;
        int fast = 0;

        int maxLen = Integer.MIN_VALUE;

        while(fast < s.length()){
            map.put(s.charAt(fast), map.getOrDefault(s.charAt(fast), 0 ) + 1);

            fast++;

            while(map.size() > 2){
                map.put(s.charAt(slow), map.get(s.charAt(slow)) - 1);

                if (map.get(s.charAt(slow)) == 0){
                    map.remove(s.charAt(slow));
                }

                slow++;
            }

            maxLen = Math.max(maxLen, fast - slow);
        }

        return maxLen;
    }
}

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