Skip to content

Commit d274506

Browse files
London | 26- SDC-Mar | beko | Sprint 2 | improve code with precomputing
1 parent e718fb4 commit d274506

2 files changed

Lines changed: 18 additions & 10 deletions

File tree

‎Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,14 @@ def find_longest_common_prefix(strings: List[str]):
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
"""
1010
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
11+
sorted_string = sorted(strings)
12+
13+
for i in range(len(sorted_string) - 1):
14+
common = find_common_prefix(
15+
sorted_string[i], sorted_string[i + 1]
16+
)
17+
if len(common) > len(longest):
18+
longest = common
1619
return longest
1720

1821

@@ -22,3 +25,7 @@ def find_common_prefix(left: str, right: str) -> str:
2225
if left[i] != right[i]:
2326
return left[:i]
2427
return left[:min_length]
28+
29+
30+
# Before: the logic force all-pairs comparison, and that results in O(n^2 * m) where n is the number of strings and m is the average string length.
31+
# After: I sort once, then compare only with adjacent pairs, improving it to O(n log n * m).

‎Sprint-2/improve_with_precomputing/count_letters/count_letters.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +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+
lowercase_letters = {letter.lower() for letter in s if letter.islower()}
6+
57
only_upper = set()
68
for letter in s:
7-
if is_upper_case(letter):
8-
if letter.lower() not in s:
9-
only_upper.add(letter)
9+
if letter.isupper() and letter.lower() not in lowercase_letters:
10+
only_upper.add(letter)
1011
return len(only_upper)
1112

1213

13-
def is_upper_case(letter: str) -> bool:
14-
return letter == letter.upper()
14+
# Before: O(n^2) for each uppercase letter, we checked if the lowercase form was in the string s itself, an O(n) scan repeated per letter.
15+
# After: precompute a set of lowercase letters seen in 's' once (O(n)), so each presence check becomes O(1), making the overall complexity O(n).

0 commit comments

Comments
 (0)