Longest Common Prefix

Find longest common prefix among strings.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 11 of 14
longest-common-prefix.py
1# Take strings
2n = int(input("Enter number of strings: "))
3strings = []
4for i in range(n):
5 strings.append(input(f"String {i+1}: "))
6
7# Find common prefix
8if not strings:
9 prefix = ""
10else:
11 prefix = strings[0]
12 for s in strings[1:]:
13 while not s.startswith(prefix):
14 prefix = prefix[:-1]
15 if not prefix:
16 break
17
18print(f"Longest common prefix: {prefix}")

Output

Enter number of strings: 3
String 1: flower
String 2: flow
String 3: flight
Longest common prefix: fl

What's going on

Start with first string, reduce until common.

Key Concepts:

Start with first string as prefix
Check each string starts with prefix
Reduce prefix until common