Longest Common Prefix Matching | Set-6 - GeeksforGeeks

12 May, 2021
Given a set of strings, find the longest common prefix.Examples:  
Input: str[] = {geeksforgeeks, geeks, geek, geezer}
Output: gee

Input: str[] = {apple, ape, april}
Output: ap
 
Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach:  
Sort the given set of N strings.
Compare the first and last string in the sorted array of strings.
The string with prefix characters matching in the first and last string will be the answer.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
PHP
Javascript
// A C++ Program to find the longest common prefix#include <bits/stdc++.h>using namespace std; // A Utility Function to find the common prefix between// first and last stringsstring commonPrefixUtil(string str1, string str2){    string result;    int n1 = str1.length(), n2 = str2.length();     // Compare str1 and str2    for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {        if (str1[i] != str2[j])            break;        result.push_back(str1[i]);    }     return (result);} // A Function that returns the longest common prefix// from the array of stringsvoid commonPrefix(string arr[], int n){    // sorts the N set of strings    sort(arr, arr + n);     // prints the common prefix of the first and the    // last string of the set of strings    cout << commonPrefixUtil(arr[0], arr[n - 1]);} // Driver Codeint main(){    string arr[] = { "geeksforgeeks", "geeks",                     "geek", "geezer" };    int n = sizeof(arr) / sizeof(arr[0]);     commonPrefix(arr, n);     return 0;}
// A Java program to find the longest common prefix import java.util.Arrays; class GFG { // A Utility Function to find the common prefix between// first and last strings    static String commonPrefixUtil(String str1, String str2) {        String result = "";        int n1 = str1.length(), n2 = str2.length();         // Compare str1 and str2        for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {            if (str1.charAt(i) != str2.charAt(j)) {                break;            }            result += str1.charAt(i);        }         return (result);    } // A Function that returns the longest common prefix// from the array of strings    static void commonPrefix(String arr[], int n) {        // sorts the N set of strings        Arrays.sort(arr);         // prints the common prefix of the first and the        // last String of the set of strings        System.out.println(commonPrefixUtil(arr[0], arr[n - 1]));    } // Driver Code    public static void main(String[] args) {        String arr[] = {"geeksforgeeks", "geeks",            "geek", "geezer"};        int n = arr.length;         commonPrefix(arr, n);     }}/* This JAVA code is contributed by 29AjayKumar*/
# A Python 3 Program to find the# longest common prefix # A Utility Function to find the common# prefix between first and last stringsdef commonPrefixUtil(str1, str2):    n1 = len(str1)    n2 = len(str2)         result = ""         # Compare str1 and str2    j = 0    i = 0    while(i <= n1 - 1 and j <= n2 - 1):        if (str1[i] != str2[j]):            break        result += (str1[i])                 i += 1        j += 1     return (result) # A Function that returns the longest# common prefix from the array of stringsdef commonPrefix(arr, n):         # sorts the N set of strings    arr.sort(reverse = False)     # prints the common prefix of the first    # and the last string of the set of strings    print(commonPrefixUtil(arr[0], arr[n - 1])) # Driver Codeif __name__ == '__main__':    arr = ["geeksforgeeks", "geeks",                    "geek", "geezer"]    n = len(arr)     commonPrefix(arr, n)     # This code is contributed by# Sanjit_Prasad
// C# Program to find the longest// common prefixusing System; class GFG{// A Utility Function to find the common// prefix between first and last stringsstatic String commonPrefixUtil(String str1,                               String str2){    string result = "";    int n1 = str1.Length, n2 = str2.Length;         // Compare str1 and str2    for (int i = 0, j = 0;             i <= n1 - 1 && j <= n2 - 1; i++, j++)    {        if (str1[i] != str2[j])            break;        result += (str1[i]);    }         return (result);} // A Function that returns the longest// common prefix from the array of stringsstatic void commonPrefix(String []arr, int n){    // sorts the N set of strings    Array.Sort(arr);     // prints the common prefix of the first    // and the last String of the set of strings    Console.Write(commonPrefixUtil(arr[0],                                   arr[n - 1]));} // Driver Codepublic static void Main(){    String []arr = {"geeksforgeeks", "geeks",                    "geek", "geezer"};    int n = arr.Length;    commonPrefix(arr, n);}} // This code is contributed by 29AjayKumar
<?php// A PHP Program to find the longest// common prefix // A Utility Function to find the common// prefix between first and last stringsfunction commonPrefixUtil($str1, $str2){    $result = "";    $n1 = strlen($str1);    $n2 = strlen($str2);     // Compare str1 and str2    for ($i = 0, $j = 0; $i <= $n1 - 1 &&          $j <= $n2 - 1; $i++, $j++)    {        if ($str1[$i] != $str2[$j])            break;        $result = $result.$str1[$i];    }     return ($result);} // A Function that returns the longest// common prefix from the array of stringsfunction commonPrefix(&$arr, $n){    // sorts the N set of strings    sort($arr);     // prints the common prefix of the first    // and the last string of the set of strings    echo commonPrefixUtil($arr[0], $arr[$n - 1]);} // Driver Code$arr = array("geeksforgeeks", "geeks",             "geek", "geezer" );$n = sizeof($arr); commonPrefix($arr, $n); // This code is contributed by ita_c?>
<script>// A Javascript program to find the longest common prefix              // A Utility Function to find the common prefix between// first and last strings    function commonPrefixUtil(str1,str2)    {        let result = "";        let n1 = str1.length, n2 = str2.length;           // Compare str1 and str2        for (let i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {            if (str1[i] != str2[j]) {                break;            }            result += str1[i];        }           return (result);    }         // A Function that returns the longest common prefix// from the array of strings    function commonPrefix(arr,n)    {        // sorts the N set of strings        arr.sort();           // prints the common prefix of the first and the        // last String of the set of strings        document.write(commonPrefixUtil(arr[0], arr[n - 1])+"<br>");    }         // Driver Code         let arr=["geeksforgeeks", "geeks",            "geek", "geezer"];         let n = arr.length;         commonPrefix(arr, n);                        // This code is contributed by avanitrachhadiya2155</script>
gee
 
Time Complexity: O(N * log N) 
29AjayKumar
Sanjit_Prasad
ukasp
avanitrachhadiya2155
prefix
Sorting Quiz
VMWare
Arrays
Strings
VMWare
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack