Skip to content

Instantly share code, notes, and snippets.

@Whoeza
Created April 7, 2024 20:10
Show Gist options
  • Save Whoeza/d43a7dd066b248f26452402837415d82 to your computer and use it in GitHub Desktop.
Save Whoeza/d43a7dd066b248f26452402837415d82 to your computer and use it in GitHub Desktop.
longest common prefix in a list of strings
# longest_prefix.py
def longest_prefix(strings_list: list[str, ...]) -> str:
if strings_list is None:
return None
if 0 == len(strings_list):
return ""
common_prefix = ""
max_prefix_length = min(
len(item)
for item in strings_list
)
complete = False
while not complete and len(common_prefix) < max_prefix_length:
target_index = len(common_prefix)
target_char = strings_list[0][target_index]
for string_index in range(len(strings_list)):
if strings_list[string_index][target_index] != target_char:
complete = True
if not complete:
common_prefix = common_prefix + target_char
return common_prefix
if __name__ == "__main__":
test_data = [
[],
[""],
["", "abc"],
["abc", "abcdef"],
["this is a test!", "this is another test!"]
]
for input_data in test_data:
print("%s" % input_data)
print("longest_prefix: %s" % longest_prefix(input_data))
print()
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment