Skip to content

Commit c10a129

Browse files
committed
find_longest_common_prefix precomputing
1 parent 134e683 commit c10a129

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed
Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
11
from typing import List
22

33

4-
def find_longest_common_prefix(strings: List[str]):
4+
def find_longest_common_prefix(strings: List[str]) -> str:
55
"""
66
find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list.
77
88
In the event that an empty list, a list containing one string, or a list of strings with no common prefixes is passed, the empty string will be returned.
99
"""
10+
11+
if not strings or len(strings) < 2:
12+
return ""
13+
14+
# Precompute sorted strings
15+
sorted_strings = sorted(strings)
1016
longest = ""
11-
for string_index, string in enumerate(strings):
12-
for other_string in strings[string_index+1:]:
13-
common = find_common_prefix(string, other_string)
14-
if len(common) > len(longest):
15-
longest = common
16-
return longest
1717

18+
for i in range(len(sorted_strings) - 1):
19+
s1, s2 = sorted_strings[i], sorted_strings[i + 1]
20+
# Find common prefix between them
21+
prefix_len = 0
22+
max_len = min(len(s1), len(s2))
23+
while prefix_len < max_len and s1[prefix_len] == s2[prefix_len]:
24+
prefix_len += 1
25+
if prefix_len > len(longest):
26+
longest = s1[:prefix_len]
1827

19-
def find_common_prefix(left: str, right: str) -> str:
20-
min_length = min(len(left), len(right))
21-
for i in range(min_length):
22-
if left[i] != right[i]:
23-
return left[:i]
24-
return left[:min_length]
28+
return longest

0 commit comments

Comments
 (0)