Longest Common Prefix

Medium ⏱ 12 min 49% acceptance ★★★★☆ 4.2
Write longest_common_prefix(strs) that returns the longest string prefix shared by every string in the list strs. If there is no common prefix, or the list is empty, return an empty string.

Examples

Example 1
Input
strs = ['flower', 'flow', 'flight']
Output
'fl'
Explanation

'fl' is the longest prefix common to all three words.

Example 2
Input
strs = ['dog', 'cat']
Output
''
Explanation

No shared prefix at all.

Constraints

  • 0 <= len(strs) <= 200

Topics

StringsSubstring Search

Companies

GoogleMicrosoftOracle

Hints

Hint 1

Start with the first string as a candidate prefix.

Hint 2

Shrink it one character at a time until every other string starts with it (`str.startswith`).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.