Skip to content

Commit 259b296

Browse files
committed
sort strs upfront
1 parent e718fb4 commit 259b296

1 file changed

Lines changed: 15 additions & 5 deletions

File tree

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,20 @@ 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 ""
1012
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
13+
14+
sorted_strings = sorted(strings)
15+
16+
for i in range(len(sorted_strings) - 1):
17+
common = find_common_prefix(
18+
sorted_strings[i],
19+
sorted_strings[i+1]
20+
)
21+
if len(common) > len(longest):
22+
longest = common
23+
1624
return longest
1725

1826

@@ -22,3 +30,5 @@ def find_common_prefix(left: str, right: str) -> str:
2230
if left[i] != right[i]:
2331
return left[:i]
2432
return left[:min_length]
33+
34+

0 commit comments

Comments
 (0)