Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Longest Common Prefix using Sorting
Next article icon

Longest Common Prefix using Sorting

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”.

Examples:

Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]
Output: “gee”
Explanation: “gee” is the longest common prefix in all the given strings: “geeksforgeeks”, “geeks”, “geeks” and “geezer”.

Input: arr[] = [“apple”, “ape”, “april”]
Output : “ap”
Explanation: “ap” is the longest common prefix in all the given strings: “apple”, “ape” and “april”.

Input: arr[] = [“hello”, “world”]
Output: “”
Explanation: There’s no common prefix in the given strings.

Approach:

The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array. Sorting is used in this approach because it makes it easier to find the longest common prefix. When we sort the strings, the first and last strings in the sorted list will be the most different from each other in terms of their characters. So, the longest common prefix for all the strings must be a prefix of both the first and the last strings in the sorted list.

Illustration:

  • Given array of strings is [“geeksforgeeks”, “geeks”, “geek”, “geezer”].
  • After sorting it becomes [“geek” ,”geeks” ,”geeksforgeeks” ,”geezer”].
  • Now, to find the longest common prefix, we only need to compare the first and last strings (“geek” and “geezer“) because any common prefix between these two will also be a prefix for all the strings in between.
  • In this case, the common prefix between “geek” and “geezer” is “gee“, which is the longest common prefix for all the strings.
C++
// C++ program to find the longest common prefix // using Sorting #include <iostream> #include <vector> #include <algorithm> using namespace std;  // Function to find the longest common prefix string longestCommonPrefix(vector<string>& arr) {      // Sort the vector of strings     sort(arr.begin(), arr.end());      // Compare the first and last strings     // in the sorted list     string first = arr.front();     string last = arr.back();     int minLength = min(first.size(), last.size());      int i = 0;        // Find the common prefix between the first     // and last strings     while (i < minLength && first[i] == last[i]) {         i++;     }      // Return the common prefix     return first.substr(0, i); }  int main() {     vector<string> arr = {"geeksforgeeks", "geeks",                            "geek", "geezer"};     cout << longestCommonPrefix(arr) << endl;      return 0; } 
Java
// Java program to find the longest common prefix // using Sorting import java.util.Arrays; class GfG {        static String longestCommonPrefix(String[] arr){                // Sort the array of strings         Arrays.sort(arr);          // Get the first and last strings after sorting         String first = arr[0];         String last = arr[arr.length - 1];         int minLength = Math.min(first.length(),                                   	last.length());                  // Find the common prefix between the first        	// and last strings       	int i = 0;         while (i < minLength &&                 first.charAt(i) == last.charAt(i)) {             i++;         }          // Return the common prefix         return first.substring(0, i);     }      public static void main(String[] args){         String[] arr = { "geeksforgeeks", "geeks",                          		"geek", "geezer" };         System.out.println(longestCommonPrefix(arr));     } } 
Python
# Python program to find the longest common prefix # using Sorting  def longestCommonPrefix(arr):      # Sort the list of strings     arr.sort()      # Get the first and last strings after sorting     first = arr[0]     last = arr[-1]     minLength = min(len(first), len(last))      i = 0     # Find the common prefix between the first     # and last strings     while i < minLength and first[i] == last[i]:         i += 1      # Return the common prefix     return first[:i]  if __name__ == "__main__":     arr = ["geeksforgeeks", "geeks", "geek", "geezer"]     print( longestCommonPrefix(arr)) 
C#
// C# program to find the longest common prefix // using Sorting using System;  class GfG {     static string LongestCommonPrefix(string[] arr){      	         // Sort the array of strings         Array.Sort(arr);          // Get the first and last strings after sorting         string first = arr[0];         string last = arr[arr.Length - 1];         int minLength = Math.Min(first.Length,                                   		last.Length);          int i = 0;         // Find the common prefix between the first and        	// last strings         while (i < minLength && first[i] == last[i]) {             i++;         }          // Return the common prefix         return first.Substring(0, i);     }      static void Main(){         string[] arr = { "geeksforgeeks", "geeks", "geek",                           "geezer" };         Console.WriteLine(LongestCommonPrefix(arr));     } } 
JavaScript
// JavaScript program to find the longest common prefix // using Sorting  function longestCommonPrefix(arr){      // Sort the array of strings     arr.sort();      // Get the first and last strings after sorting     let first = arr[0];     let last = arr[arr.length - 1];     let minLength = Math.min(first.length, last.length);      let i = 0;          // Find the common prefix between the first and      // last strings     while (i < minLength && first[i] === last[i]) {         i++;     }      // Return the common prefix     return first.substring(0, i); }  // Driver Code let arr = ["geeksforgeeks", "geeks", "geek", "geezer"]; console.log(longestCommonPrefix(arr) ); 

Output
gee 

Time Complexity: O(n*m*log n), to sort the array, where n is the number of strings and m is the length of longest string.
Auxiliary Space: O(m) to store the strings first, last and result.

Other Approaches

  • Longest Common Prefix Word by Word Matching
  • Longest Common Prefix Character by Character Matching
  • Longest Common Prefix Divide and Conquer
  • Longest Common Prefix Binary Search
  • Longest Common Prefix Using Trie

Next Article
Longest Common Prefix using Sorting

A

anugum2xzm
Improve
Article Tags :
  • Strings
  • Sorting
  • DSA
  • Arrays
  • Longest Common Prefix
Practice Tags :
  • Arrays
  • Sorting
  • Strings

Similar Reads

    Longest Common Prefix using Trie
    Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”.Examples:Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: “gee”Explanation: “gee” is the lon
    7 min read
    Longest Common Prefix using Binary Search
    Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "".Examples:Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: "gee" is the lon
    8 min read
    Longest Common Prefix
    Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”.Examples:Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: “gee”Explanation: “gee” is the lon
    5 min read
    Longest Common Prefix using Linked List
    Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using
    14 min read
    Longest Common Prefix using Word by Word Matching
    Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "".Examples:Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: “gee” is the lon
    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