DSA interview question
A command-line tool offers tab completion: when several filenames match what the user has typed, it fills in as many characters as all of them share. That's the longest common prefix of a list of strings. The straightforward way compares the strings column by column until some string runs out or disagrees. A neat alternative sorts the list and compares only the first and last strings, because they're the most different.
Example: ["flower", "flow", "flight"] → "fl".
string longestCommonPrefix(const vector<string>& strs); // strs is non-empty
Input strs | Output | Explanation |
|---|---|---|
["flower", "flow", "flight"] | "fl" | |
["dog", "racecar", "car"] | "" | They differ at the first character |
["interview", "internet", "interval", "internal"] | "inter" | |
["a"] | "a" | A single string is its own prefix |
["", "b"] | "" | An empty string limits the prefix |
["abc", "abc"] | "abc" | Identical strings |
(Confirm: the list is non-empty; strings may be empty; comparison is case-sensitive.)
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