DevPath

← All problems

Longest Common Prefix

Easy strings

Description

Return the longest common prefix shared by all strings, or an empty string if there is none.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account