DSA interview question
A compression engine gets its best ratios on stretches of text that use few distinct characters. Given a string and k, find the length of the longest substring with at most k distinct characters. It's the general version of "fruit into baskets" (k = 2): grow a window on the right while counting characters, and when the number of distinct characters exceeds k, shrink from the left until one character's count drops to zero.
Example: s = "eceba", k = 2 → 3 ("ece").
int lengthOfLongestSubstringKDistinct(const string& s, int k);
Input (s, k) | Output | Explanation |
|---|---|---|
("eceba", 2) | 3 | "ece" |
("aa", 1) | 2 | |
("aabacbebebe", 3) | 7 | "cbebebe" |
("abaccc", 2) | 4 | "accc" |
("abc", 0) | 0 | No characters allowed |
(Confirm: substring means contiguous; k ≥ 0; characters are arbitrary bytes.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in