Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions Sprint-2/improve_with_precomputing/common_prefix/common_prefix.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ def find_longest_common_prefix(strings: List[str]):
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.
"""
longest = ""
for string_index, string in enumerate(strings):
for other_string in strings[string_index+1:]:
common = find_common_prefix(string, other_string)
if len(common) > len(longest):
longest = common
sorted_string = sorted(strings)

for i in range(len(sorted_string) - 1):
common = find_common_prefix(
sorted_string[i], sorted_string[i + 1]
)
if len(common) > len(longest):
longest = common
return longest


Expand All @@ -22,3 +25,7 @@ def find_common_prefix(left: str, right: str) -> str:
if left[i] != right[i]:
return left[:i]
return left[:min_length]


# 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.
# After: I sort once, then compare only with adjacent pairs, improving it to O(n log n * m).
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ def count_letters(s: str) -> int:
"""
count_letters returns the number of letters which only occur in upper case in the passed string.
"""
lowercase_letters = {letter.lower() for letter in s if letter.islower()}

only_upper = set()
for letter in s:
if is_upper_case(letter):
if letter.lower() not in s:
only_upper.add(letter)
if letter.isupper() and letter.lower() not in lowercase_letters:
only_upper.add(letter)
return len(only_upper)


def is_upper_case(letter: str) -> bool:
return letter == letter.upper()
# 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.
# 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).
Loading