Skip to content
Related Articles

Related Articles

Python | Ways to determine common prefix in set of strings

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 22 Jun, 2022
View Discussion
Improve Article
Save Article

Given a set of strings, write a Python program to determine common prefix from a set of strings. Given below are a few methods to solve the above task.
Method #1: Using Naive Approach 
 

Python3




# Python code to demonstrate
# to find common prefix
# from set of strings
 
# Initialising string
ini_strlist = ['akshat', 'akash', 'akshay', 'akshita']
 
# Finding common prefix using Naive Approach
res = ''
prefix = ini_strlist[0]
 
for string in ini_strlist[1:]:
    while string[:len(prefix)] != prefix and prefix:
        prefix = prefix[:len(prefix)-1]
    if not prefix:
        break
res = prefix
 
# Printing result
print("Resultant prefix", str(res))

Output: 

Resultant prefix ak

 

  
Method #2: Using itertools.takewhile and zip 
 

Python3




# Python code to demonstrate
# to find common prefix
# from set of strings
 
from itertools import takewhile
 
# Initialising string
ini_strlist = ['akshat', 'akash', 'akshay', 'akshita']
 
# Finding common prefix using Naive Approach
res = ''.join(c[0] for c in takewhile(lambda x:
        all(x[0] == y for y in x), zip(*ini_strlist)))
 
# Printing result
print("Resultant prefix", str(res))

Output: 

Resultant prefix ak

 

Complexity Analysis:

In both the solution time and space complexity are the same:

Time Complexity: O(n2)

Space Complexity: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!