Skip to content

Commit 7b09829

Browse files
committed
Optimise common_prefix: sort list to compare only neighbours
1 parent 134e683 commit 7b09829

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,24 @@ 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 list is empty or has 1 item, no pairs exist.
11+
if len(strings) < 2:
12+
return ""
13+
14+
strings.sort()
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+
# We only need to compare neighbours.
19+
for i in range(len(strings) - 1):
20+
first_string = strings[i]
21+
second_string = strings[i + 1]
22+
23+
common = find_common_prefix(first_string, second_string)
24+
25+
if len(common) > len(longest):
26+
longest = common
27+
1628
return longest
1729

1830

0 commit comments

Comments
 (0)