Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Longest Common Prefix by vtflnk
def longest_prefix(strings: list[str]) -> str:
"""
Determines the longest common prefix among a list of strings.
Returns an empty string if no common prefix exists.
"""
if not strings:
return ""
# Start with the first string as the potential prefix
prefix = strings[0]
# Compare the prefix with each subsequent string
for string in strings[1:]:
# Reduce the prefix until it matches the start of the string
while string[:len(prefix)] != prefix and prefix:
prefix = prefix[:-1] # Remove the last character from the prefix
if not prefix:
return "" # Return early if no common prefix exists
return prefix
print("Example:")
print(repr(longest_prefix(["flower", "flow", "flight"])))
# These "asserts" are used for self-checking
assert longest_prefix(["flower", "flow", "flight"]) == "fl"
assert longest_prefix(["dog", "racecar", "car"]) == ""
assert longest_prefix(["apple", "application", "appetizer"]) == "app"
assert longest_prefix(["a"]) == "a"
assert longest_prefix(["", "b"]) == ""
assert longest_prefix(["same", "same", "same"]) == "same"
assert longest_prefix(["mismatch", "mister", "miss"]) == "mis"
assert longest_prefix(["alphabet", "alpha", "alphadog"]) == "alpha"
assert longest_prefix(["book", "boot", "booster"]) == "boo"
assert longest_prefix(["short", "shore", "shot"]) == "sho"
print("The mission is done! Click 'Check Solution' to earn rewards!")
Jan. 7, 2025
Comments: