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 strings2n = int(input("Enter number of strings: "))3strings = []4for i in range(n):5 strings.append(input(f"String {i+1}: "))67# Find common prefix8if 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 break1718print(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
🔗Related Content
- 📖
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- 📝
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- 💻
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum