easyStringArrays & Hashing

Longest Common Prefix

easyTime: O(n*m)Space: O(1)

The shape of the problem

Given a list of strings, return the longest prefix shared by all of them. Empty string if there is no common prefix (including the case of an empty list).

Signals to notice

prefix across all stringscolumn-wise comparisonearly termination

Brute force first

Pick the first string, then for each other string, shrink the prefix one character at a time until it matches. Correct, but every shrink rescans.

The key insight

The longest common prefix cannot be longer than the shortest string. Column-wise scanning stops at exactly the first disagreement, so you never look past that column.

Trace it on strs=["flower","flow","flight"]

i=0  strs[0][0]="f" all match  → keep
i=1  strs[0][1]="l" all match  → keep
i=2  strs[0][2]="o" strs[2][2]="i" mismatch
return strs[0][0..2) = "fl"

What must stay true

At column i, `strs[0][0..i)` is a prefix of every string in the list.

Shape of the loop

for i in 0..len(strs[0]):
  c = strs[0][i]
  for s in strs[1..]:
    if i == len(s) or s[i] != c:
      return strs[0][0..i]
return strs[0]

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not guarding against a string shorter than the current index. Accessing `strs[k][i]` when `i >= len(strs[k])` is either a crash or an unintended match depending on the language.

Arrays & Hashing Pattern