Column by column
Find the longest start that every word shares. About 8 minutes.
Read down the columns
Your phone's contacts search shows "fl" when names like "flower", "flow" and "flight" all start with it. How do you find the longest start they all share?
Line the words up on the left. The first column holds every word's first letter, the second column every second letter. The shared start continues for as long as each column holds the same letter all the way down.
Column 0: f, f, f. All the same, keep going.
Stop at the first problem
Two things end the shared start: a letter that differs, or a word that has run out of letters. Either way, stop right there. The answer is the first word, cut to that length.
Check the length before reading a letter. Asking for the fifth letter of a four-letter word is an error in most languages.
if not words:
return ""
for i, ch in enumerate(words[0]):
for w in words[1:]:
if i >= len(w) or w[i] != ch:
return words[0][:i]
return words[0]What is the longest shared start of "flower", "flow" and "flight"?
- A"fl"
- B"flow"
- C"f"
Show the answer
"fl". Columns 0 and 1 are f, l everywhere; column 2 has o, o and i.
Longest shared start
Return the longest string that every word in the list starts with. For an empty list, return "".
words = ["flower", "flow", "flight"] → "fl"
0 ≤ words ≤ 200 · 0 ≤ each length ≤ 200 · only a to z