Topic 3 of 21 · Beginner
Strings & Hashing
Hash maps and sets for O(1) lookups — the most used tool in interviews.
Concept
A hash map stores key → value pairs. A hash function turns the key into a bucket index, giving average O(1) insert, delete and lookup.
Use counting maps for anagrams, frequency problems and grouping.
Strings are immutable in Python and Java: building a string in a loop with + is O(n²); use a list and join, or StringBuilder.
Complexity
| Operation | Time | Space |
|---|---|---|
| Insert / lookup / delete | O(1) average | O(n) |
| Worst case (collisions) | O(n) | — |
Code (Python)
from collections import Counter, defaultdict
def is_anagram(a, b):
return Counter(a) == Counter(b)
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())Remember
- “Have I seen this before?” → set.
- “How many times?” → counter map.
- Sorted string or char-count tuple makes a good grouping key.
Practice these interview problems
- Valid Anagram
- Group Anagrams
- First Unique Character
- Longest Consecutive Sequence
Lesson test
Take an 8-question test on “Strings & Hashing” — concepts, output prediction, bug spotting and interview questions.