livepython.net

228. Python Program to Find the Longest Common Start of Words

HardPhase 3 · Challenge

This one takes a few steps. It uses split(), startswith(), slicing and a while loop. You know all of them. Try a short example on paper first.

Overview

Finding the longest common start of some words is a classic interview question. Programmers often call it the longest common prefix. Search boxes use the same idea to fill in a word while you type.

Problem Statement

Olga sorts files whose names begin in the same way. Olga wants the longest start that all the names share.

A start of a word is its first letter or first few letters. For example, f, fl and flo are starts of flower. A whole word is a start of itself too.

Read a line of words. Find the longest start that every word has. Print Common start: <start>. If the words do not even share their first letter, print No common start.

Examples

Example 1. Input flower flow flight gives:

Common start: fl

Why: all three words begin with fl. The third letters are o, o and i, so flo is not shared.

Example 2. Input dog racecar car gives:

No common start

Why: the first letters are d, r and c. They are all different, so the words share no start at all.

Input

One line of words, with one space between them (1 word or more). Each word has small letters only, from a to z. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line: Common start:, a space and the start, or No common start. The tests try 10 different inputs, also one word, two equal words and a word that is the start of all the others.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 12 · Working With Strings
solution.py
# write your code here

EXPECTED OUTPUT

1Common start: fl

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.