InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Longest Common Prefix

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug