FastPrepLongest Substring With At Most Two Distinct Characters
Problem · Sliding Window

Longest Substring With At Most Two Distinct Characters

Learn this problem
MediumByteDance logoByteDanceFULLTIMEPHONE SCREEN

Problem statement

Given a string s, return the length of its longest contiguous substring containing at most two distinct characters.

A substring must occupy consecutive positions. Repeated occurrences of one character count as one distinct character. An empty string has answer 0.

Function

longestTwoDistinct(s: String) → int

Examples

Example 1

s = "eceba"return = 3

The substring ece has length 3 and uses only e and c. Every longer substring contains at least three distinct characters.

Example 2

s = "ccaabbb"return = 5

The substring aabbb has length 5. Adding either preceding c would introduce a third distinct character.

Constraints

  • 0 <= s.length <= 50000
  • s contains only lowercase English letters.

More ByteDance problems

drafts saved locally
public int longestTwoDistinct(String s) {
    // Write your code here
}
s"eceba"
expected3
checking account