Longest common prefix
Python data engineering interview problem. Difficulty: beginner. Pattern: Strings. About 8 minutes. Free to practice.
Find the longest string that every word starts with. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A catalog search can suggest a shared beginning while the user types several product names. Return the longest string that every word starts with. If the words do not share a first character, or the list is empty, return an empty string. Write lcp(words: list[str]) -> str. flower, flow and flight all begin with fl, so the answer is 'fl'. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Compare all words, not only the first two.
- Stop before the first mismatch.
- Return the prefix string itself.
Constraints
- Words are strings and comparison is case-sensitive.
- The return type is str.
Examples
Input: lcp(["flower", "flow", "flight"]) Output: 'fl' All three start with 'fl'; the third letter differs.
Topics: lakebench, python, prefix, strings.
More Python interview questions · All interview problems · Learn data engineering
Longest common prefix
Interview-style drill: Find the longest string that every word starts with.
Implement `lcp(words: list[str]) -> str` that returns the longest prefix shared by all the words. Return `""` when there is no common prefix or when the list is empty.