python / python-control-flow
20 mins
Python Level 8: Frequency Maps & Set Optimizations
Why This Matters: Using Python dicts and sets turns O(N²) quadratic loops into O(N) linear time.
## Frequency Counting Pattern
Using hash dictionaries to achieve O(1) average lookup times.
```python
def char_frequency(text: str) -> dict:
freq = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
return freq
print(char_frequency("growcode"))
```
MENTAL MODEL & MEMORY LAYOUT
FREQUENCY MAP PIPELINE:
"growcode" ──► Iterates chars ──► Dict {'g':1, 'r':1, 'o':2, 'w':1, 'c':1, 'd':1, 'e':1} COMMON PITFALLS TO AVOID
- Accessing missing dictionary key `dict[key]` without using `.get()` or `in` check (raises KeyError).
Duplicate Detection via Hash Set
def has_duplicates(items):
return len(items) != len(set(items))
print(has_duplicates([1, 2, 3, 1])) # TrueCompares list length to unique set length for O(N) duplicate detection.
CONCEPT MASTERY CHECKPOINT
What is the average lookup time complexity for checking `item in my_set` in Python?
NEXT RECOMMENDED LESSON
Python Level 9: Standard Library
Challenge: Find first non-repeating character index in string.