DSA interview question
Back at the plagiarism-detection system you designed the hashing theory for — now your tech lead wants the actual search algorithm implemented: given a text and a pattern, find all starting indices where pattern occurs in text, using a rolling hash so you don't recompute the hash from scratch at every window position. This is Rabin-Karp — average-case O(n+m), with a worst-case fallback to verify matches character-by-character to guard against hash collisions.
Example: text = "ABABDABACDABABCABAB", pattern = "ABABCABAB" → pattern occurs at index 10.
vector<int> rabinKarp(string text, string pattern);
text | pattern | Output (indices) | Explanation |
|---|---|---|---|
"ABABDABACDABABCABAB" | "ABABCABAB" | [10] | Single occurrence at index 10 |
"AAAAA" | "AA" | [0,1,2,3] | Overlapping matches allowed |
"ABCABCABC" | "ABC" | [0,3,6] | Multiple non-overlapping matches |
"ABCDEF" | "XYZ" | [] | No occurrence |
"AAAA" | "AAAAA" | [] | Pattern longer than text |
"hello world hello" | "hello" | [0,12] | Two separate matches |
"aaa" | "a" | [0,1,2] | Single-char pattern, every position matches |
"AA" in "AAAA")? (Yes typically — confirm.)text and pattern? (Large inputs reinforce need for O(n+m) average case via rolling hash, not recomputing each window's hash from scratch — which would be O(n*m).)hash(s[i..i+m-1]) to hash(s[i+1..i+m]) in O(1)?"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