13
13
*/
14
14
package com .thealgorithms .strings ;
15
15
import java .util .Arrays ; // Specific import
16
-
17
16
// To find the longest Common Prefix of String array
18
- public class LongestCommonPrefix {
19
-
17
+ public final class LongestCommonPrefix {
20
18
// Private constructor to prevent instantiation of utility class
21
19
private LongestCommonPrefix () {
22
20
}
23
-
24
21
// Method to find the longest common prefix
25
22
public static String longestPrefix (String [] str ) {
26
23
int n = str .length ;
@@ -43,10 +40,9 @@ public static String longestPrefix(String[] str) {
43
40
break ;
44
41
}
45
42
}
46
-
47
43
return first .substring (0 , i );
48
44
}
49
-
45
+
50
46
// Main method to run test cases
51
47
public static void main (String [] args ) {
52
48
// Test cases
@@ -72,22 +68,13 @@ public static void main(String[] args) {
72
68
73
69
/*
74
70
Time and Space Complexity:
75
- Time Complexity:O(n log n + m)
76
-
77
- Sorting the array takes π(π log π)
78
- O(nlogn), where n is the number of strings.
79
- Comparing the first and last string takes π(π)
80
- O(m), where m is the length of the shortest string.
81
- Overall, the time complexity is
82
- π(log π + π )
83
-
84
-
85
- Space Complexity:O(n)
86
-
87
- Sorting requires π(π)
88
- O(n) space for the array.
89
- The space complexity for storing the prefix result is
90
- π(1)
91
- O(1) since it depends on the length of the prefix, which is part of the input.
92
- Therefore, the space complexity is π(π)
93
- */
71
+ Time Complexity: O(n log n + m)
72
+ - Sorting the array takes O(n log n), where n is the number of strings.
73
+ - Comparing the first and last string takes O(m), where m is the length of the shortest string.
74
+ - Overall, the time complexity is O(n log n + m).
75
+
76
+ Space Complexity: O(n)
77
+ - Sorting requires O(n) space for the array.
78
+ - The space complexity for storing the prefix result is O(1), since it depends on the length of the prefix, which is part of the input.
79
+ Therefore, the space complexity is O(n).
80
+ */
0 commit comments