Skip to content

Commit 4df41d6

Browse files
author
Mrinal Chauhan
committed
Longest Common Prefix
1 parent 2a805c8 commit 4df41d6

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

β€Žsrc/main/java/com/thealgorithms/strings/LongestCommonPrefix.java

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,11 @@
1313
*/
1414
package com.thealgorithms.strings;
1515
import java.util.Arrays; // Specific import
16-
1716
// To find the longest Common Prefix of String array
18-
public class LongestCommonPrefix {
19-
17+
public final class LongestCommonPrefix {
2018
// Private constructor to prevent instantiation of utility class
2119
private LongestCommonPrefix() {
2220
}
23-
2421
// Method to find the longest common prefix
2522
public static String longestPrefix(String[] str) {
2623
int n = str.length;
@@ -43,10 +40,9 @@ public static String longestPrefix(String[] str) {
4340
break;
4441
}
4542
}
46-
4743
return first.substring(0, i);
4844
}
49-
45+
5046
// Main method to run test cases
5147
public static void main(String[] args) {
5248
// Test cases
@@ -72,22 +68,13 @@ public static void main(String[] args) {
7268

7369
/*
7470
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

Comments
Β (0)