Longest Substring with At Most K Distinct Characters
MediumSliding Windowsliding window
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given a string s and an integer k, return the length of the longest contiguous substring of s that contains **at most** k distinct characters.
If k is 0 or s is empty, the answer is 0. Target O(n) time.
Examples
Input: s = "eceba", k = 2
Output: 3
"ece" uses only the characters e and c.
Input: s = "aa", k = 1
Output: 2
The whole string uses just one distinct character.
Constraints
- 0 <= s.length <= 5 * 10^4
- 0 <= k <= 50
- `s` consists of lowercase English letters.
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.