Longest Common Prefix
Easy strings
Description
Constraints
1 <= words <= 1000
Examples
Input: words = ["flower","flow","flight"]
Output: "fl"
Hints (1)
- Compare characters column by column across every word.
Solutions
Shrink the candidate prefix. (requires "strings") · Time O(n*m) · Space O(1)
func longestCommonPrefix(words []string) string {
if len(words) == 0 {
return ""
}
prefix := words[0]
for _, w := range words {
for len(prefix) > 0 && !strings.HasPrefix(w, prefix) {
prefix = prefix[:len(prefix)-1]
}
}
return prefix
}
Shrink the candidate prefix against each word. · Time O(n*m) · Space O(1)
function longestCommonPrefix(words) {
if (!words.length) return '';
let prefix = words[0];
for (const w of words) while (!w.startsWith(prefix)) prefix = prefix.slice(0, -1);
return prefix;
}
Shrink the candidate prefix against each word. · Time O(n*m) · Space O(1)
function longestCommonPrefix($words) {
if (empty($words)) { return ''; }
$prefix = $words[0];
foreach ($words as $w) {
while ($prefix !== '' && strpos($w, $prefix) !== 0) {
$prefix = substr($prefix, 0, -1);
}
}
return $prefix;
}
Shrink the candidate prefix against each word. · Time O(n*m) · Space O(1)
def longestCommonPrefix(words):
if not words:
return ""
prefix = words[0]
for w in words:
while not w.startswith(prefix):
prefix = prefix[:-1]
return prefix
Shrink the candidate prefix against each word. · Time O(n*m) · Space O(1)
function longestCommonPrefix(words: string[]): string {
if (!words.length) return '';
let prefix = words[0];
for (const w of words) while (!w.startsWith(prefix)) prefix = prefix.slice(0, -1);
return prefix;
}
Create a free account to submit solutions, track progress and save problems.
Create account