Longest Common Prefix

EasyStrings · Vertical Scanning🧩 String ManipulationLeetCode #14 ↗Updated

Problem

Given an array of strings strs, return the longest string that every element starts with. If the strings do not even share their first character, return the empty string "".
Input["stamp","stack","stair"]Output"sta"
Input["cat","dog"]Output""
Input["abc","ab","abcd"]Output"ab"

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

Try it yourself

Java
class Solution {
    public String longestCommonPrefix(String[] strs) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Read the strings column by column: the prefix grows while every string has the same character at index c, and the first mismatch or the end of the shortest string fixes the answer — no character beyond it is ever needed.
PatternString Manipulation

Instinct Reading, comparing or rebuilding text character by character? Walk indices on a char[] and build output with a StringBuilder, never with + in a loop.

Memory hack Chars in an array, pointers on the ends, builder at the back - strings are just arrays wearing a costume.

Open the String Manipulation guide →

Approaches

Brute ForceTry Every Prefix of the First String

Time O(n · m2)Space O(m)

The answer must be a prefix of strs[0] (length m). Try lengths from m down to 0 and return the first candidate that every string startsWith; the empty prefix always qualifies.

Java
public String longestCommonPrefix(String[] strs) {
    String first = strs[0];
    for (int len = first.length(); len > 0; len--) {
        String cand = first.substring(0, len);
        boolean ok = true;
        for (String s : strs) {
            if (!s.startsWith(cand)) { ok = false; break; }
        }
        if (ok) return cand; // longest length that works
    }
    return "";
}

Obviously correct, but re-checks the same leading characters for every length.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every Prefix of the First StringO(n · m2)O(m)
BetterHorizontal Scan (Shrink a Running Length)O(S)O(1) extra
OptimalVertical Scan (Column by Column)O(n · (L+1)) ≤ O(S)O(1) extra
Common pitfalls
  • Reading strs[i].charAt(c) before checking its length — index out of bounds.
  • Returning null instead of "" when nothing is shared.
  • Forgetting a single-string array — the whole string is the answer.
Interview tips
  • Say out loud that the answer can never be longer than the shortest string.
  • Compare horizontal vs vertical scanning and why vertical stops sooner.
  • Mention the trie approach for many repeated prefix queries.
Pattern
Vertical (column-wise) scan → a property that must hold at the same index across many strings.
My notes saved in this browser