Skip to content

Commit a35d066

Browse files
committed
perf: optimize count_letters via pre-computed character set
- Replace O(N) string scanning with O(1) set lookup - Transition overall algorithm complexity from O(N^2) to O(N) - Maintain legacy loop structure and helper functions for minimal code changes - Add documentation explaining the pre-computing strategy
1 parent c8b0c59 commit a35d066

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
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.
4+
5+
Optimized via Pre-computing: We convert the string to a set upfront to make
6+
the 'not in' check a constant-time operation.
47
"""
8+
# PRE-COMPUTING: Create a set of all unique characters in the string.
9+
# Searching a set takes O(1) time, while searching a string takes O(N) time.
10+
chars_in_string = set(s)
11+
512
only_upper = set()
13+
# LEGACY LOOP: Iterate through the string as originally designed.
614
for letter in s:
715
if is_upper_case(letter):
8-
if letter.lower() not in s:
16+
# OPTIMIZATION: Check against the pre-computed set instead of the full string 's'.
17+
if letter.lower() not in chars_in_string:
918
only_upper.add(letter)
1019
return len(only_upper)
1120

1221

1322
def is_upper_case(letter: str) -> bool:
14-
return letter == letter.upper()
23+
return letter == letter.upper()

0 commit comments

Comments
 (0)