Start free

Expert · String algorithms · 250 of 264

Common beginning

Print the longest beginning that all words share, or none if they share nothing.

Input: words on one line. Output: the common prefix, or none

Examples

Input
flower flow flight
Output
fl
Input
dog racecar car
Output
none
Input
same same
Output
same

One more test checks other inputs when you press Check.

Stuck? The idea behind string algorithms

Finding patterns in text: compare a window of the text with the pattern as it slides along, or use what has already matched to skip ahead.

str.find(pattern, start) gives the next position, or -1 when there is none.

text, pat = "abababa", "aba"
i = text.find(pat)
while i != -1:
    print(i)
    i = text.find(pat, i + 1)

Watch for: Matches can overlap ("aba" twice in "ababa"): move on by one, not by the pattern's length.

All the string algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More string algorithms exercises