DSA interview question
You're working on a DNA/genome sequence analysis tool (or, more relatably, a log-deduplication system for compressed network packets). A "happy prefix" of a string is defined as a prefix that is also a suffix, but is not the entire string itself (no full overlap). Your task: given a string s, return the longest happy prefix. If no such prefix exists, return an empty string.
Example: s = "level" → the longest happy prefix is "l" (since "l" is both a prefix and a suffix of "level", and no longer prefix qualifies — "leve" is a prefix but not a suffix).
string longestHappyPrefix(string s);
Input s | Output | Explanation |
|---|---|---|
"level" | "l" | "l" is prefix & suffix; "le", "lev", "leve" aren't suffixes too |
"ababab" | "abab" | "abab" is both prefix and suffix, longest such match |
"leetcodeleet" | "leet" | "leet" appears as both prefix and suffix |
"a" | "" | Single char — prefix would equal the whole string, not allowed |
"aaaa" | "aaa" | "aaa" is prefix & suffix, can't use full "aaaa" (that's the whole string) |
"abcabcabc" | "abcabc" | Longest non-trivial prefix=suffix match |
"abcdefg" | "" | No prefix matches any suffix |
s?"s (e.g., for "aaaa", prefix "aaa" (indices 0-2) and suffix "aaa" (indices 1-3) overlap in index range — is that allowed)? — Yes, index overlap is fine; only full-string overlap (proper-ness) is disallowed. This is a common point of confusion, good to clarify explicitly.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