← Back to problems Solve on LeetCode →

Longest Substring with At Most K Distinct

LeetCode 340 • Hard • Sliding Window

Input: s = "eceba", k = 2 → Output: 3 (ece or eba). Sliding window + char count map. Shrink when distinct > k.

TimeO(n)
SpaceO(k)
left: — right: — maxLen: —
Window
Right
Shrink
left—
right—
count—
maxLen—
Ready
Press Play. Sliding window: expand right, add to count map. If distinct > k, shrink from left until valid.