Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Arrays & Hashing

Longest Common Prefix

EASY✓ CHIP-TIMEDLC #14 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • the list holds at least one string
  • strings may vary widely in length, including empty ones
  • lowercase letters only, on this course
  • the result is empty when there is no shared opening across all strings
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 hintstake 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 boardthe 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 splitstwo paces, two languages

grind/longest-common-prefix.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED