Skip to the solution
EasyDSA10 min read

How do you find the longest common prefix of an array of strings?

742 views

The problem

Question presented to candidate: "Write a function that takes a list of strings and returns the longest prefix they all share, or an empty string if there is none. For example, flower, flow and flight give fl. Please write it in Python."

What a strong answer should cover:

  • Vertical scanning: compare character i of every string, stop at the first mismatch or the first string that runs out; return strs[0][:i].
  • Edge cases handled up front: empty list, a single string, an empty string in the list.
  • O(n * (L + 1)) time, bounded by the total characters S; O(1) extra space besides the result.
  • Alternatives named with their cost: horizontal scanning, sorting and comparing the first and last strings, a trie for many queries.
  • Python specifics: zip(*strs) stops at the shortest string, min(strs)/max(strs) give the lexicographic extremes without sorting, and os.path.commonprefix is character-based, not path-based.

Clarifying questions expected:

  • "What should an empty list return?"
  • "Is it case-sensitive?"

Code / implementation expected: Yes โ€” longest_common_prefix(strs) in Python; a short loop, with the zip idiom as a nice variant.

  • dsa
  • strings

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonVertical scanning on normal and edge-case inputs
PythonVertical vs horizontal vs sort-the-ends, counting character comparisons

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 17 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is space complexity, and how much stack space does recursion use?

Continue