Skip to content

Commit 3aa1e75

Browse files
committed
improve code for finding common prefix
1 parent deb4e14 commit 3aa1e75

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ def find_longest_common_prefix(strings: List[str]):
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+
if len(strings) < 2:
11+
return ""
12+
13+
# Precompute: Sort so similar strings are near each other
14+
strings = sorted(strings)
15+
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
17+
18+
for i in range(len(strings) - 1) :
19+
common = find_common_prefix(strings[i], strings[i+1])
20+
if len(common) > len(longest):
21+
longest = common
1622
return longest
1723

1824

0 commit comments

Comments
 (0)