Skip to content

Commit 29c50d3

Browse files
author
Mrinal Chauhan
committed
Longest Common Prefix
1 parent e499d3b commit 29c50d3

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
Β (0)