DSA interview question
You're building the "find in file" feature for a code editor (think Ctrl+F / Ctrl+Shift+F in VS Code), but the files being searched are massive log files (gigabytes) and the same search is run repeatedly. Naive substring search is too slow for the SLAs your team has committed to. Your task: given a text and a pattern, find all starting indices in text where pattern occurs, in O(n + m) time using the KMP algorithm.
Example: text = "ABABDABACDABABCABAB", pattern = "ABABCABAB" → pattern occurs at index 10.
vector<int> kmpSearch(string text, string pattern);
text | pattern | Output (indices) | Explanation |
|---|---|---|---|
"ABABDABACDABABCABAB" | "ABABCABAB" | [10] | Single occurrence starting at index 10 |
"AAAAA" | "AA" | [0,1,2,3] | Overlapping occurrences allowed |
"ABCABCABC" | "ABC" | [0,3,6] | Multiple non-overlapping occurrences |
"ABCDEF" | "XYZ" | [] | No occurrence found |
"AAAA" | "AAAAA" | [] | Pattern longer than text |
"" | "A" | [] | Empty text |
"A" | "" | edge case | Empty pattern — clarify expected behavior with interviewer |
"AA" in text "AAAA" — does it count at indices 0,1,2)? (Yes, typically — confirm.)text and pattern? (If very large — like 10⁶+ — this strongly signals the interviewer wants O(n+m), ruling out brute force O(n*m).)std::string::find in a loop?"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