1
+ package com .thealgorithms .strings ;
2
+ import java .util .*;
3
+ //To find the longest Common Prefix of String array
4
+ public class longestCommonPrefix {
5
+ public static String longestPrefix (String [] str ){
6
+ int n =str .length ;
7
+ Arrays .sort (str );
8
+ if (n ==0 ){
9
+ return "" ;
10
+ }
11
+ String first =str [0 ];
12
+ String last =str [n -1 ];
13
+ int len =Math .min (first .length (),last .length ());
14
+ int i ;
15
+ for (i =0 ;i <len ;i ++){
16
+ if (first .charAt (i )!=last .charAt (i )){
17
+ break ;
18
+ }
19
+ }
20
+ return first .substring (0 , i );
21
+
22
+ }
23
+ public static void main (String args []){
24
+ //Input test case
25
+ String [] arr = {"flower" , "flow" , "flight" };
26
+
27
+ // Output the result
28
+ System .out .println ("Longest Common Prefix: " + longestPrefix (arr )); //flo
29
+ }
30
+ }
31
+ /*
32
+ Time and Space Complexity:
33
+ Time Complexity:O(n log n + m)
34
+
35
+ Sorting the array takes π(π log π)
36
+ O(nlogn), where n is the number of strings.
37
+ Comparing the first and last string takes π(π)
38
+ O(m), where m is the length of the shortest string.
39
+ Overall, the time complexity is
40
+ π(log π + π )
41
+
42
+
43
+ Space Complexity:O(n)
44
+
45
+ Sorting requires π(π)
46
+ O(n) space for the array.
47
+ The space complexity for storing the prefix result is
48
+ π(1)
49
+ O(1) since it depends on the length of the prefix, which is part of the input.
50
+ Therefore, the space complexity is π(π)
51
+ */
0 commit comments