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 array of strings ; find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Function to test other function
using System ; public class GFG { static string longestCommonPrefix ( String [ ] a ) { int size = a . Length ; if ( size == 0 ) return " " ; if ( size == 1 ) return a [ 0 ] ; Array . Sort ( a ) ; int end = Math . Min ( a [ 0 ] . Length , a [ size - 1 ] . Length ) ; int i = 0 ; while ( i < end && a [ 0 ] [ i ] == a [ size - 1 ] [ i ] ) i ++ ; string pre = a [ 0 ] . Substring ( 0 , i ) ; return pre ; } public static void Main ( ) { string [ ] input = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; Console . WriteLine ( " The ▁ longest ▁ Common " + " ▁ Prefix ▁ is ▁ : ▁ " + longestCommonPrefix ( input ) ) ; } }