DSA interview question
A genetics lab scans DNA-like strings and wants to know how many substrings contain exactly K different symbols, a measure of local diversity. Checking every substring is O(n²) or worse. The key trick is that "exactly K" is awkward for a sliding window, but "at most K" is easy: for each right end, the window of valid left ends is a single range. So compute atMost(K) − atMost(K − 1), where each term is a linear sliding window.
Example: ("aba", 2) → 3 (the substrings "ab", "ba" and "aba").
long long countExactlyK(const string& s, int k); // lowercase letters
Input (s, k) | Output | Explanation |
|---|---|---|
("aba", 2) | 3 | "ab", "ba", "aba" |
("abaaca", 1) | 7 | Runs a, b, aa (3 substrings), c, a |
("abc", 3) | 1 | Only "abc" |
("aa", 1) | 3 | "a", "a", "aa" |
("abc", 4) | 0 | Only 3 distinct letters exist |
("abcbaa", 3) | 8 | Every substring containing a, b and c |
(Confirm: substrings are counted by position, so equal substrings at different positions count separately; lowercase letters only.)
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