14. Longest Common Prefix
Asked at 52Bloomberg79Apple76Google74Amazon74Microsoft72Meta71CME Group100opentext84tcs73IBM63Revolut100USAA100Yelp94Target88Disney88oyo88Nokia87Sigmoid87Wipro85Pwc83HSBC81SAP81persistent systems78Publicis Sapient77Virtusa77EPAM Systems77Larsen & Toubro71Quora71Adobe69Capgemini68Fidelity68Deloitte65Zoho65PhonePe64Infosys63Hudson River Trading63American Express62Deutsche Bank62HashedIn62Yahoo61Walmart Labs60Palo Alto Networks59Jane Street59Qualcomm58Barclays53TikTok50Oracle49Visa48Accenture44Nvidia39Roblox37Uber35
Problem
Return the longest string that is a prefix of every string in strs, or "" if they share no common prefix.
Example: ["flower","flow","flight"] → "fl"; ["dog","racecar","car"] → ""
Vertical scan: compare column i of every string with the first string; stop at the first mismatch or end of any string.
Complexity: O(total characters).
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
first = strs[0]
for i, ch in enumerate(first):
for s in strs[1:]:
if i == len(s) or s[i] != ch:
return first[:i]
return first
assert Solution().longestCommonPrefix(["flower", "flow", "flight"]) == "fl"
assert Solution().longestCommonPrefix(["dog", "racecar", "car"]) == ""
class Solution {
public String longestCommonPrefix(String[] strs) {
String first = strs[0];
for (int i = 0; i < first.length(); i++)
for (String s : strs)
if (i == s.length() || s.charAt(i) != first.charAt(i)) return first.substring(0, i);
return first;
}
}
func longestCommonPrefix(strs []string) string {
first := strs[0]
for i := 0; i < len(first); i++ {
for _, s := range strs[1:] {
if i == len(s) || s[i] != first[i] {
return first[:i]
}
}
}
return first
}