◀ THE GRIND — ARRAYS & HASHING

Longest Common Prefix

The drill: Every word in the list opens with some shared run of characters — possibly empty. Measure exactly how far that agreement stretches before the first word breaks ranks.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A list of strings arrives, and hidden inside them is some shared run of characters that every single one starts with — the job is to measure exactly how long that shared opening is.

The moment any string in the list disagrees with the others at some position, the shared prefix stops there; the result reports everything up to but not including that break.

If the strings share nothing from the very first character, the answer is an empty string — that's a perfectly valid outcome, not a failure case that needs special handling.

EX 01
strs = ["training", "trail", "train"]
"trai"
SPLITS AT THE FIFTH COLUMN
EX 02
strs = ["pace", "pacer", "paces"]
"pace"
THE SHORTEST WORD IS THE PREFIX
EX 03
strs = ["fartlek", "tempo", "surge"]
""
NO AGREEMENT AT COLUMN ZERO
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

The answer can never outlast the shortest word, and one disagreement anywhere caps it for good. What's the cheapest way to find the FIRST disagreement?

HINT 2 THE STRUCTURE

Compare column by column instead of word by word: position 0 across every word, then position 1, and so on. The first column that isn't unanimous ends the prefix.

HINT 3 ONE STEP FROM THE ANSWER

Walk the first word's characters; at index i, any other word that is only i long or differs there marks the cut. Survive the whole walk and the entire first word is the answer.

COACH'S BOARD — THE PATTERN, STEP BY STEP
COLUMN BY COLUMNPATTERN · COLUMN SCANstrs = ["training", "trail", "train"]
t
r
a
i
n
i
n
g
t
r
a
i
l
t
r
a
i
n
STEP 1

Three words: training, trail, train. Walk column by column until one word disagrees.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/longest-common-prefix.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        first = strs[0]
        for i, ch in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != ch:
                    return first[:i]    # first non-unanimous column
        return first
TIME O(N·M)SPACE O(1)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED