Skip to content

Commit ac294de

Browse files
committed
Replace Counter with set in count_letters for efficiency and update comment
1 parent 78e64e5 commit ac294de

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
from collections import Counter
22
def count_letters(s: str) -> int:
33
#Returns the number of letters which only occur in uppercase in the passed string
4-
letters = Counter(s) #count occurrences of each character
4+
letters = set(s)
55
only_upper = 0
66
for letter in letters:
7-
if letter.isupper():
8-
if letter.lower() not in letters:
7+
if letter.isupper() and letter.lower() not in letters:
98
only_upper += 1
109
return only_upper
11-
#The first implementation was O(n² * m) in the worst case comparing every pair of strings character by character.
12-
# Now,
13-
#Counter scans the string once O(n)
14-
#Checking letter.lower() in letters O(1) per letter
15-
#Total time O(n + u) where u is the number of unique letters
10+
# Convert the string to a set to remove duplicate characters in O(n)
11+
# Iterate over unique letters and check lowercase membership in O(1)
12+
# Total time complexity: O(n)
13+
# Space complexity: O(u), where u is the number of unique characters

0 commit comments

Comments
 (0)