DSA interview question
You're optimizing the same "find in file" search engine, but this time your tech lead wants to evaluate an alternative to KMP — the Z-algorithm — because it generalizes more cleanly to multi-pattern matching and some plagiarism-detection pipelines your team is exploring. Your task: given a string s, compute its Z-array, where Z[i] is the length of the longest substring starting at index i that is also a prefix of s (with Z[0] conventionally defined as 0 or len(s), depending on convention — clarify this with your interviewer).
Example: s = "aabcaabxaaaz" → Z = [0,1,0,0,3,1,0,0,2,2,1,0].
vector<int> zFunction(string s);
Input s | Output Z | Explanation |
|---|---|---|
"aabcaabxaaaz" | [0,1,0,0,3,1,0,0,2,2,1,0] | Z[4]=3 because "aab" at index 4 matches prefix "aab" |
"aaaa" | [0,3,2,1] | Each position matches a decreasing-length prefix of all-'a's |
"abcabcabc" | [0,0,0,6,0,0,3,0,0] | Z[3]=6, full repeating match of "abcabc" |
"aaa" | [0,2,1] | Simple repeated character case |
"a" | [0] | Single character — trivially 0 by convention |
"" | [] | Empty string edge case |
"abab" | [0,0,2,0] | Z[2]=2 because "ab" at index 2 matches prefix "ab" |
(Always verify with your actual implementation — Z[0] convention varies by source, confirm with interviewer before assuming.)
Z[i] is the length of the longest common prefix between s and s[i:]."Z[0]? (Most standard implementations either leave it 0 or set it to len(s) — clarify and state your choice explicitly, since both are used in literature.)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