CodingNodes / Arrays & Hashing / Longest Common Prefix System design Space play · ←→ step · R restart

Problem

You are given a list of words. Return the longest string that every word in the list starts with.

If the words share no starting letters at all, return the empty string.

Constraints

  • 1 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] uses lowercase English letters only

Examples: pick one to animate

Solutions

TimeO(S) SpaceO(1)

Time: S is the total number of letters in all words. Each letter is looked at at most once, and we stop at the first mismatch.

Space: Only the column index and a reference to the first word are kept. The returned prefix is the output.

Use the first word as a reference. For each column i, check that every other word has the same letter there. The first word that is too short or has a different letter ends the scan, and the answer is everything before column i.