InterviewPrepKit

Home / Coding / Arrays & Hashing

Longest Common Prefix

easy Original β†—
Solving tips
  • Think in columns, not rows: compare character position i across all strings and stop at the first column where any string disagrees or ends.
  • The LCP can never exceed the shortest string, so guard i >= len(s) before reading s[i]; return first[:i] at the first mismatch. O(S) time (S = total chars), O(1) extra space.
  • Elegant alternative: the LCP of the whole list equals the LCP of just min(strs) and max(strs) lexicographically.
  • Pitfall: an empty string in the list means the answer is '' β€” don't crash or return None.

Problem

Given a list of strings strs, return the longest string that is a prefix of every string in the list. If the strings share no leading characters at all, return the empty string "".

Examples

  • Input: strs = ["flower", "flow", "flight"] β†’ Output: "fl" All three start with "fl"; they disagree at the third character (o vs i).
  • Input: strs = ["dog", "racecar", "car"] β†’ Output: "" There is no character that all three strings start with.
  • Input: strs = ["interspecies", "interstellar", "interstate"] β†’ Output: "inters" All share "inters"; the next characters are p, t, t β€” not unanimous.

Constraints

  • 1 <= len(strs) <= 200
  • 0 <= len(strs[i]) <= 200
  • Strings consist of lowercase English letters (possibly empty)

With S = total characters across all strings, O(S) is the target; anything polynomial passes at these sizes.

Think about it first

Hint 1 The common prefix can never be longer than the shortest string in the list. Why?
Hint 2 Instead of comparing whole strings, compare one *column* at a time: do all strings agree on character 0? On character 1?
Hint 3 Column-by-column: for position i, take the i-th character of the first string and check it against every other string; stop at the first mismatch (or when some string runs out) and return the first string sliced up to i.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.