MediumHash TableStringSliding Window

Longest Substring with At Most K Distinct Characters

LeetCode
1 approach, code in all languages

Given a string s and an integer k, find the length of the longest contiguous substring that contains no more than k distinct characters.

If k is zero, no characters may appear, so the answer is zero.

Example 1

Input: s = "eceba", k = 2

Output: 3

The block "ece" uses only the two distinct characters e and c.

Example 2

Input: s = "aabbcc", k = 1

Output: 2

With only one distinct character allowed, a run like "aa" is the longest possible.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • 0 <= k <= 5 * 10^4
  • s consists of English letters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now