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
iof every string, stop at the first mismatch or the first string that runs out; returnstrs[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, andos.path.commonprefixis 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.