Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Find Most common elements set
Next article icon

Python Program To Find Longest Common Prefix Using Sorting

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Problem Statement: Given a set of strings, find the longest common prefix.
Examples: 

Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee"  Input: {"apple", "ape", "april"} Output: "ap"

The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {"apple", "ape", "zebra"}, there is no common prefix because the 2 most dissimilar strings of the array "ape" and "zebra" do not share any starting characters. 
We have discussed five different approaches in below posts.  

  1. Word by Word Matching
  2. Character by Character Matching
  3. Divide and Conquer
  4. Binary Search.
  5. Using Trie) 

In this post a new method based on sorting is discussed. The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array.

Python 3
# Python 3 program to find longest  # common prefix of given array of words. def longestCommonPrefix( a):          size = len(a)      # if size is 0, return empty string      if (size == 0):         return ""      if (size == 1):         return a[0]      # sort the array of strings      a.sort()          # find the minimum length from      # first and last string      end = min(len(a[0]), len(a[size - 1]))      # find the common prefix between      # the first and last string      i = 0     while (i < end and             a[0][i] == a[size - 1][i]):         i += 1      pre = a[0][0: i]     return pre  # Driver Code if __name__ == "__main__":      input = ["geeksforgeeks", "geeks",                       "geek", "geezer"]     print("The longest Common Prefix is :" ,                  longestCommonPrefix(input))  # This code is contributed by ita_c 

Output
The longest Common Prefix is : gee 


Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array and MAX is maximum number of characters in any string. Please note that comparison of two strings would take at most O(MAX) time and for sorting n strings, we would need O(MAX * n * log n ) time. 

Space Complexity: O(1) as no extra space has been used.

Please refer complete article on Longest Common Prefix using Sorting for more details!


Next Article
Python Program to Find Most common elements set
author
kartik
Improve
Article Tags :
  • Strings
  • Sorting
  • Python Programs
  • DSA
  • Longest Common Prefix
Practice Tags :
  • Sorting
  • Strings

Similar Reads

  • Python Program To Find Longest Common Prefix Using Word By Word Matching
    Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose
    4 min read
  • Python Program for Longest Common Subsequence
    LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So
    3 min read
  • Python Program to Find Most common elements set
    Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
    5 min read
  • Python Program to Group Strings by K length Using Suffix
    Given Strings List, the task is to write a Python program to group them into K-length suffixes. Input : test_list = ["food", "peak", "geek", "good", "weak", "sneek"], K = 3 Output : {'ood': ['food', 'good'], 'eak': ['peak', 'weak'], 'eek': ['geek', 'sneek']} Explanation : words ending with ood are f
    5 min read
  • Python program to find the longest word in a sentence
    In this article, we will explore various methods to find the longest word in a sentence. Using LoopFirst split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths. [GFGTABS] Python s =
    1 min read
  • Python program to Concatenate Kth index words of String
    Given a string with words, concatenate the Kth index of each word. Input : test_str = 'geeksforgeeks best geeks', K = 3 Output : ktk Explanation : 3rd index of "geeksforgeeks" is k, "best" has 't' as 3rd element. Input : test_str = 'geeksforgeeks best geeks', K = 0 Output : gbg Method #1 : Using joi
    4 min read
  • Python Program to find the Larger String without Using Built-in Functions
    Given two strings. The task is to find the larger string without using built-in functions. Examples: Input: GeeksforGeeks Geeks Output: GeeksforGeeks Input: GeeksForFeeks is an good Computer Coding Website It offers several topics Output: GeeksForFeeks is an good Computer Coding Website Step-by-step
    3 min read
  • Python - Ways to determine common prefix in set of strings
    A common prefix is the longest substring that appears at the beginning of all strings in a set. Common prefixes in a set of strings can be determined using methods like os.path.commonprefix() for quick results, itertools.takewhile() combined with zip() for a more flexible approach, or iterative comp
    2 min read
  • Python Program to Check Overlapping Prefix - Suffix in Two Lists
    Given 2 Strings, our task is to check overlapping of one string's suffix with prefix of other string. Input : test_str1 = "Gfgisbest", test_str2 = "bestforall" Output : best Explanation : best overlaps as suffix of first string and prefix of next. Input : test_str1 = "Gfgisbest", test_str2 = "restfo
    4 min read
  • Python Program to print strings based on the list of prefix
    Given a Strings List, the task here is to write a python program that can extract all the strings whose prefixes match any one of the custom prefixes given in another list. Input : test_list = ["geeks", "peeks", "meeks", "leeks", "mean"], pref_list = ["ge", "ne", "me", "re"] Output : ['geeks', 'meek
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences