Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]consists of only lowercase English letters.
This solution uses the vertical scanning technique with optimized performance:
- Early Exit Strategy: Check if first string is empty and return early if needed
- Vertical Scanning: Compare characters at the same position across all strings
- StringBuilder Optimization: Use
StringBuilderfor efficient string building instead of string concatenation - Smart Loop Control: Use
&& isEqualcondition to exit loop early when mismatch is found - Immediate Returns: Return immediately when a mismatch is detected, avoiding unnecessary iterations
- Boundary Checks: Ensure we don't exceed string lengths during comparison
- Initialize
StringBuilderfor efficient string building andisEqualflag for control flow - Check if the first string is empty and return early if so
- For each character position
iin the first string (with early exit condition):- Get the character at position
ifrom the first string - Compare this character with the character at position
iin all other strings - If any string is shorter or has a different character, return the current prefix immediately
- If all match, append the character to the result
- Get the character at position
- Return the complete prefix
class Solution {
public String longestCommonPrefix(String[] strs) {
boolean isEqual = true;
StringBuilder prefix = new StringBuilder();
if (strs[0].isEmpty()) {
isEqual = false;
return prefix.toString();
}
for (int i = 0; i < strs[0].length() && isEqual; i++){
char firstChar = strs[0].charAt(i);
for (String w : strs) {
if ((w.isEmpty()) || (i>= w.length())) {
isEqual = false;
return prefix.toString();
}
if (w.charAt(i) == firstChar) {
isEqual = true;
}
else{
isEqual = false;
return prefix.toString();
}
}
if(isEqual){
prefix.append(firstChar);
}
else{
return prefix.toString();
}
}
return prefix.toString();
}
}- Time Complexity: O(S) where S is the sum of all characters in all strings
- Space Complexity: O(1) for the algorithm logic + O(m) for the output string, where m is the length of the common prefix
- Runtime: 1 ms - Beats 61.57% of Java submissions
- Memory Usage: 41.44 MB - Beats 77.31% of Java submissions
- StringBuilder vs String Concatenation: Using
StringBuilder.append()instead of+=reduces time complexity from O(m²) to O(m) for string building - Smart Loop Control: Using
&& isEqualin the for loop condition allows early termination when mismatch is detected - Immediate Returns: Multiple return statements provide early exits at the first sign of mismatch, avoiding unnecessary comparisons
- Efficient Character Comparison: Direct character comparison using
charAt()instead of substring operations - Boolean Flag Optimization: Using
isEqualflag to control flow and minimize redundant checks
- Horizontal Scanning: Compare strings pairwise and reduce the prefix
- Binary Search: Use binary search on the prefix length
- Divide and Conquer: Recursively find common prefixes of subarrays
- Problem: 14. Longest Common Prefix
- Solution: My Submission
Array String Vertical Scanning StringBuilder Optimization