Skip to content

Commit d08b10b

Browse files
committed
improve with precomputing
1 parent 134e683 commit d08b10b

File tree

2 files changed

+29
-25
lines changed

2 files changed

+29
-25
lines changed
Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,31 @@
11
from typing import List
22

3-
4-
def find_longest_common_prefix(strings: List[str]):
3+
def find_longest_common_prefix(strings: List[str]) -> str:
54
"""
6-
find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list.
7-
8-
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.
5+
Returns the longest string common at the start of any two strings in the list.
96
"""
7+
if len(strings) < 2:
8+
return ""
9+
10+
# Precompute the set of prefixes for each string
11+
prefixes = {}
12+
for s in strings:
13+
prefixes[s] = [s[:i] for i in range(1, len(s) + 1)]
14+
1015
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)
16+
n = len(strings)
17+
for i in range(n):
18+
for j in range(i + 1, n):
19+
# Compare prefixes of strings[i] and strings[j] efficiently
20+
common = _common_prefix_precomputed(prefixes[strings[i]], strings[j])
1421
if len(common) > len(longest):
1522
longest = common
16-
return longest
1723

24+
return longest
1825

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]
26+
def _common_prefix_precomputed(prefix_list: List[str], other: str) -> str:
27+
# Find the longest prefix of other that exists in prefix_list
28+
for prefix in reversed(prefix_list):
29+
if other.startswith(prefix):
30+
return prefix
31+
return ""
Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
def count_letters(s: str) -> int:
22
"""
3-
count_letters returns the number of letters which only occur in upper case in the passed string.
3+
Returns the number of letters which only occur in upper case in the passed string.
44
"""
5-
only_upper = set()
6-
for letter in s:
7-
if is_upper_case(letter):
8-
if letter.lower() not in s:
9-
only_upper.add(letter)
10-
return len(only_upper)
11-
5+
# Precompute sets of lowercase and uppercase letters in the string
6+
lower_letters = {c for c in s if c.islower()}
7+
upper_letters = {c for c in s if c.isupper()}
128

13-
def is_upper_case(letter: str) -> bool:
14-
return letter == letter.upper()
9+
# Count letters that appear only in uppercase
10+
only_upper = {c for c in upper_letters if c.lower() not in lower_letters}
11+
return len(only_upper)

0 commit comments

Comments
 (0)