Leetcode 14. Longest Common Prefix
The problem is to write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string “”.
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
["flower"]
?""
.n
) could be up to 200 and the length of each string (m
) could be up to 200 characters.public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
// Start with the first string as the common prefix.
String commonPrefix = strs[0];
for (int i = 1; i < strs.length; i++) {
commonPrefix = findCommonPrefix(commonPrefix, strs[i]);
if (commonPrefix.isEmpty()) {
break;
}
}
return commonPrefix;
}
// Helper method to find common prefix between two strings
private String findCommonPrefix(String str1, String str2) {
int minLength = Math.min(str1.length(), str2.length());
int i = 0;
while (i < minLength && str1.charAt(i) == str2.charAt(i)) {
i++;
}
return str1.substring(0, i);
}
// Main method for testing purposes
public static void main(String[] args) {
Solution solution = new Solution();
String[] strs1 = {"flower", "flow", "flight"};
System.out.println("Test Case 1: " + solution.longestCommonPrefix(strs1)); // Expected output: "fl"
String[] strs2 = {"dog", "racecar", "car"};
System.out.println("Test Case 2: " + solution.longestCommonPrefix(strs2)); // Expected output: ""
}
}
This approach ensures efficient performance by progressively narrowing down the common prefix, checking only the necessary characters, and stopping early when a mismatch is found.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?