PPractick

DSA interview question

Longest Common Prefix

Easy · Algorithms · Topics: string

The problem

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".

Function signature

string longestCommonPrefix(const vector<string>& strs);  // strs is non-empty

Test cases

Input strsOutputExplanation
["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.)

How interviewers phrase it

Clarifying questions to ask

  1. Can the list be empty? Can strings be empty?
  2. Case-sensitive?
  3. How many strings and how long? (Affects which approach is best.)

Follow-ups to expect

  1. "What's the vertical scanning approach?"
  2. "How does sorting help?"
  3. "What about divide and conquer or binary search on the length?"
  4. "When would a trie be better?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in