Longest Common Prefix using Sorting | C ++ program to find longest common prefix of given array of words . ; If size is 0 , return empty string ; Sort the given array ; Find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Code
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; string longestCommonPrefix ( string ar [ ] , int n ) { if ( n == 0 ) return " " ; if ( n == 1 ) return ar [ 0 ] ; sort ( ar , ar + n ) ; int en = min ( ar [ 0 ] . size ( ) , ar [ n - 1 ] . size ( ) ) ; string first = ar [ 0 ] , last = ar [ n - 1 ] ; int i = 0 ; while ( i < en && first [ i ] == last [ i ] ) i ++ ; string pre = first . substr ( 0 , i ) ; return pre ; } int main ( ) { string ar [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; cout << " The ▁ longest ▁ common ▁ prefix ▁ is : ▁ " << longestCommonPrefix ( ar , n ) ; return 0 ; }