Longest Common Prefix using Sorting
Last Updated : 14 Nov, 2024
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) );
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
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