Longest Common Prefix

Find longest common prefix among strings.

Logic BuildingAdvanced
Logic Building
# Take strings
n = int(input("Enter number of strings: "))
strings = []
for i in range(n):
    strings.append(input(f"String {i+1}: "))

# Find common prefix
if not strings:
    prefix = ""
else:
    prefix = strings[0]
    for s in strings[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                break

print(f"Longest common prefix: {prefix}")

Output

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

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