Please be brutal, and treat this as if I was at an interview at a top 5 tech firm.
Question: Write a function to find the longest common prefix string amongst an array of strings.
Time it took: 17 minutes
Worst case complexity analysis: n possible array elements, each can have length m that we are traversing, hence O(n*m); m could be a constant, since it's rare to find a string with length, so in a sense, I imagine this could be treated as O(n *constant length(m)) = O(n)?
Space complexity analysis: O(n)
public String longestCommonPrefix(String[] strs) {
String longestPrefix = "";
if(strs.length>0){
longestPrefix = strs[0];
}
for(int i=1; i<strs.length; i++){
String analyzing = strs[i];
int j=0;
for(; j<Math.min(longestPrefix.length(), strs[i].length()); j++){
if(longestPrefix.charAt(j) != analyzing.charAt(j)){
break;
}
}
longestPrefix = strs[i].substring(0, j);
}
return longestPrefix;
}
getCommonPrefix
\$\endgroup\$