KatInterview

159. Longest Substring with At Most Two Distinct Characters

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the longest substring of a given string s that contains at most two distinct characters. This is a classic example of a problem that can be efficiently solved using the sliding window technique.

Solution

Longest Substring with At Most Two Distinct Characters in Python

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        n = len(s)
        if n < 3:
            return n

        left = 0
        max_len = 0
        char_counts = {}

        for right in range(n):
            # Expand the window by including the character at the right pointer
            char_right = s[right]
            char_counts[char_right] = char_counts.get(char_right, 0) + 1

            # Shrink the window from the left if it contains more than 2 distinct characters
            while len(char_counts) > 2:
                char_left = s[left]
                char_counts[char_left] -= 1
                if char_counts[char_left] == 0:
                    del char_counts[char_left]
                left += 1

            # Update the maximum length found so far
            max_len = max(max_len, right - left + 1)

        return max_len

Longest Substring with At Most Two Distinct Characters in Java

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int n = s.length();
        if (n < 3) {
            return n;
        }

        int left = 0;
        int maxLength = 0;
        Map<Character, Integer> charCount = new HashMap<>();

        for (int right = 0; right < n; right++) {
            // Expand the window by including the character at the right pointer
            char c = s.charAt(right);
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);

            // Shrink the window from the left if it contains more than 2 distinct characters
            while (charCount.size() > 2) {
                char leftChar = s.charAt(left);
                charCount.put(leftChar, charCount.get(leftChar) - 1);
                if (charCount.get(leftChar) == 0) {
                    charCount.remove(leftChar);
                }
                left++;
            }

            // Update the maximum length found so far
            maxLength = Math.max(maxLength, right - left + 1);
        }

        return maxLength;
    }
}

Longest Substring with At Most Two Distinct Characters in C++

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int n = s.length();
        if (n < 3) {
            return n;
        }

        int left = 0;
        int maxLength = 0;
        unordered_map<char, int> charCount;

        for (int right = 0; right < n; ++right) {
            // Expand the window by including the character at the right pointer
            charCount[s[right]]++;

            // Shrink the window from the left if it contains more than 2 distinct characters
            while (charCount.size() > 2) {
                char leftChar = s[left];
                charCount[leftChar]--;
                if (charCount[leftChar] == 0) {
                    charCount.erase(leftChar);
                }
                left++;
            }

            // Update the maximum length found so far
            maxLength = max(maxLength, right - left + 1);
        }

        return maxLength;
    }
};

Longest Substring with At Most Two Distinct Characters in TypeScript

function lengthOfLongestSubstringTwoDistinct(s: string): number {
    const n = s.length;
    if (n < 3) {
        return n;
    }

    let left = 0;
    let maxLength = 0;
    const charCount = new Map<string, number>();

    for (let right = 0; right < n; right++) {
        // Expand the window by including the character at the right pointer
        const char = s[right];
        charCount.set(char, (charCount.get(char) || 0) + 1);

        // Shrink the window from the left if it contains more than 2 distinct characters
        while (charCount.size > 2) {
            const leftChar = s[left];
            const count = charCount.get(leftChar)!;
            if (count === 1) {
                charCount.delete(leftChar);
            } else {
                charCount.set(leftChar, count - 1);
            }
            left++;
        }

        // Update the maximum length found so far
        maxLength = Math.max(maxLength, right - left + 1);
    }

    return maxLength;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.