DSA Factory
Free Strings lessonsStrings · Stage 4 · Parsing · Step 3

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.

One column at a time: all the same letter? keep going.
words = ["flower", "flow", "flight"], lined up on the left
012345
flower
f
l
o
w
e
r
flow
f
l
o
w
flight
f
l
i
g
h
t

Column 0: f, f, f. All the same, keep going.

Move 1 of 4

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.

Short word? check the length before reading.
In code
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]
Quick check

What is the longest shared start of "flower", "flow" and "flight"?

  1. A"fl"
  2. B"flow"
  3. C"f"
Show the answer

"fl". Columns 0 and 1 are f, l everywhere; column 2 has o, o and i.

Your problem

Longest shared start

Return the longest string that every word in the list starts with. For an empty list, return "".

Example
words = ["flower", "flow", "flight"] → "fl"

0 ≤ words ≤ 200 · 0 ≤ each length ≤ 200 · only a to z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve