Skip to content

Commit c2b06f5

Browse files
committed
Improved code by pre-computing.
1 parent 134e683 commit c2b06f5

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,26 @@
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+
if len(strings) < 2:
11+
return ""
12+
13+
# PRE-COMPUTE by sorting strings once
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+
#compare only strings that are next to eacotherr in sorted order
19+
for i in range(len(strings) - 1):
20+
common = find_common_prefix(strings[i], strings[i + 1])
21+
if len(common) > len(longest):
22+
longest = common
23+
1624
return longest
1725

1826

0 commit comments

Comments
 (0)