Skip to content

Commit 030a262

Browse files
committed
This is the implementation of improve_with_precomputing
1 parent 134e683 commit 030a262

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,26 @@ 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 not strings or len(strings) == 1:
11+
return ""
12+
1013
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
14+
15+
# Precompute: Build a dictionary of prefixes to their count
16+
# For each string, generate all its prefixes and count occurrences
17+
prefix_count = {}
18+
19+
for string in strings:
20+
seen_prefixes = set() # Avoid counting same prefix twice from same string
21+
for i in range(len(string) + 1):
22+
prefix = string[:i]
23+
if prefix not in seen_prefixes:
24+
prefix_count[prefix] = prefix_count.get(prefix, 0) + 1
25+
seen_prefixes.add(prefix)
26+
27+
# Find the longest prefix that appears in at least 2 strings
28+
for prefix, count in prefix_count.items():
29+
if count >= 2 and len(prefix) > len(longest):
30+
longest = prefix
31+
1632
return longest
17-
18-
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]

Sprint-2/improve_with_precomputing/count_letters/count_letters.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@ def count_letters(s: str) -> int:
22
"""
33
count_letters returns the number of letters which only occur in upper case in the passed string.
44
"""
5+
# Precompute: create set of all lowercase letters in the string (O(n))
6+
lowercase_letters = set(c for c in s if c.islower())
7+
8+
# Now just count uppercase letters that don't have a lowercase version
59
only_upper = set()
610
for letter in s:
711
if is_upper_case(letter):
8-
if letter.lower() not in s:
12+
if letter.lower() not in lowercase_letters:
913
only_upper.add(letter)
1014
return len(only_upper)
1115

0 commit comments

Comments
 (0)