- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find longest common prefix from list of strings in Python
Suppose we have a list of lowercase strings, we have to find the longest common prefix.
So, if the input is like ["antivirus", "anticlockwise", "antigravity"], then the output will be "anti"
To solve this, we will follow these steps −
sort the list words alphabetically
- prefix := a new list
- flag := 0
- for i in range 0 to size of words[0], do
- for each j in words, do
- if j[i] is not same as last element of prefix, then
- delete last element from prefix
- flag := 1
- come out from the loop
- if j[i] is not same as last element of prefix, then
- if flag is same as 1, then
- come out from the loop
- for each j in words, do
- return string after concatenating all elements present in prefix array
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, words): words.sort() prefix = [] flag = 0 for i in range(len(words[0])): prefix.append(words[0][i]) for j in words: if j[i] != prefix[-1]: prefix.pop() flag = 1 break if flag == 1: break return ''.join(prefix) ob = Solution() words = ["antivirus", "anticlockwise", "antigravity"] print(ob.solve(words))
Input
["antivirus", "anticlockwise", "antigravity"]
Output
anti
- Related Articles
- Longest Common Prefix in Python
- Program to find length of longest common subsequence of three strings in Python
- Python Program to print strings based on the list of prefix
- How to find the longest common substring from more than two strings in Python?
- Find minimum shift for longest common prefix in C++
- Program to perform prefix compression from two strings in Python
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Program to find length longest prefix sequence of a word array in Python
- Program to find length of longest interval from a list of intervals in Python
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find length of longest common subsequence in C++
- Program to find length of longest common substring in C++
- C++ Program to Find the Longest Prefix Matching of a Given Sequence

Advertisements