→ An answer that can only shrink as you see more input
→ Compare everything against one running candidate
These clues point to Running State in One Pass: Walk the input once and keep a few variables (best so far, minimum so far, a count) that summarise everything seen.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
return prefix;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Time O(S), where S is the total number of characters Space O(1) extra
Take strs[0] as the prefix. For each other word, while it doesn't start with the prefix, drop the prefix's last character. If the prefix becomes empty, stop early.
Approach 1
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
}
Verdict: Simple and fast; each character is removed from the prefix at most once.
2
Vertical scan: column by column
Time O(S) Space O(1)
Compare character j of every word. The first column where a word ends or a character differs marks the end of the prefix.