Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Longest Substring with At Most K Distinct Characters
Problem
Given a string s and an integer k, return the length of the longest contiguous substring that contains no more than k different characters. If k is 0, the answer is 0.
shas between 1 and 50,000 characters, drawn from printable ASCII.kis between 0 and 60.
Examples
s = "pqpqrps", k = 2→4."pqpq"uses onlypandq; therthat follows would be a third character.s = "zz", k = 1→2. A single distinct character throughout.s = "mnomno", k = 0→0. No characters are allowed at all.
Hints
- When a window first holds
k + 1different characters, which characters could you drop from the left to get back tok, and how far would that take the left edge? - Keep a count of each character currently inside a window, and note that "how many distinct characters" is just the number of keys with a positive count.
- Variable-size sliding window: extend
hi, and while the map has more thankkeys, removes[lo]and delete keys whose count reaches zero.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.