Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-012

Longest Common Prefix

Problem

Return the longest common prefix shared by every string in the list strs.

If the list is empty, or the strings share no leading character, return the empty string. For example, the longest common prefix of flower, flow and flight is fl.

Hint

Start with the first string as the prefix and shrink it until every other string starts with it.

Test cases

case 1
in: [["flower","flow","flight"]]
expected: "fl"
case 2
in: [["dog","racecar","car"]]
expected: ""
case 3
in: [[]]
expected: ""
case 4
in: [["abc"]]
expected: "abc"
case 5
in: [["","b"]]
expected: ""
Starter codePython
def longest_common_prefix(strs):
    # Your code here
    pass

5 test cases · run your code against them in the editor