Related Articles

# Longest Common Prefix using Sorting

• Difficulty Level : Medium
• Last Updated : 27 Apr, 2021

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.

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.

## C++

 `// C++ program to find longest common prefix``// of given array of words.``#include``#include` `using` `namespace` `std;` `// Function to find the longest common prefix``string longestCommonPrefix(string ar[], ``int` `n)``{` `    ``// If size is 0, return empty string``    ``if` `(n == 0)``        ``return` `""``;` `    ``if` `(n == 1)``        ``return` `ar;` `    ``// Sort the given array``    ``sort(ar, ar + n);` `    ``// Find the minimum length from``    ``// first and last string``    ``int` `en = min(ar.size(),``                 ``ar[n - 1].size());` `    ``// Now the common prefix in first and``    ``// last string is the longest common prefix``    ``string first = ar, last = ar[n - 1];``    ``int` `i = 0;``    ``while` `(i < en && first[i] == last[i])``        ``i++;` `    ``string pre = first.substr(0, i);``    ``return` `pre;``}` `// Driver Code``int` `main()``{``    ``string ar[] = {``"geeksforgeeks"``, ``"geeks"``,``                           ``"geek"``, ``"geezer"``};``    ``int` `n = ``sizeof``(ar) / ``sizeof``(ar);``    ``cout << ``"The longest common prefix is: "``         ``<< longestCommonPrefix(ar, n);``    ``return` `0;``}` `// This code is contributed by jrolofmeister`

## Java

 `// Java program to find longest common prefix of``// given array of words.``import` `java.util.*;` `public` `class` `GFG``{``    ``public` `String longestCommonPrefix(String[] a)``    ``{``        ``int` `size = a.length;` `        ``/* if size is 0, return empty string */``        ``if` `(size == ``0``)``            ``return` `""``;` `        ``if` `(size == ``1``)``            ``return` `a[``0``];` `        ``/* sort the array of strings */``        ``Arrays.sort(a);` `        ``/* find the minimum length from first and last string */``        ``int` `end = Math.min(a[``0``].length(), a[size-``1``].length());` `        ``/* find the common prefix between the first and``           ``last string */``        ``int` `i = ``0``;``        ``while` `(i < end && a[``0``].charAt(i) == a[size-``1``].charAt(i) )``            ``i++;` `        ``String pre = a[``0``].substring(``0``, i);``        ``return` `pre;``    ``}` `    ``/* Driver Function to test other function */``    ``public` `static` `void` `main(String[] args)``    ``{``        ``GFG gfg = ``new` `GFG();``        ``String[] input = {``"geeksforgeeks"``, ``"geeks"``, ``"geek"``, ``"geezer"``};``        ``System.out.println( ``"The longest Common Prefix is : "` `+``                                   ``gfg.longestCommonPrefix(input));``    ``}``}`

## 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`

## C#

 `// C# program to find longest common prefix of``// given array of words.``using` `System;``        ` `public` `class` `GFG {``    ` `    ``static` `string` `longestCommonPrefix(String[] a)``    ``{``        ``int` `size = a.Length;` `        ``/* if size is 0, return empty string */``        ``if` `(size == 0)``            ``return` `""``;` `        ``if` `(size == 1)``            ``return` `a;` `        ``/* sort the array of strings */``        ``Array.Sort(a);` `        ``/* find the minimum length from first``        ``and last string */``        ``int` `end = Math.Min(a.Length,``                            ``a[size-1].Length);` `        ``/* find the common prefix between the``        ``first and last string */``        ``int` `i = 0;``        ``while` `(i < end && a[i] == a[size-1][i] )``            ``i++;` `        ``string` `pre = a.Substring(0, i);``        ``return` `pre;``    ``}` `    ``/* Driver Function to test other function */``    ``public` `static` `void` `Main()``    ``{``        ` `        ``string``[] input = {``"geeksforgeeks"``, ``"geeks"``,``                                 ``"geek"``, ``"geezer"``};``                                 ` `        ``Console.WriteLine( ``"The longest Common"``                              ``+ ``" Prefix is : "``                  ``+ longestCommonPrefix(input));``    ``}``}` `// This code is contributed by Sam007.`

## Javascript

 ``

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.
This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.