Hash Maps & Sets
Data Structures
Preview
Hash maps
seen = {}\nseen["ama"] = 25\nif "ama" in seen: # O(1) check\n print(seen["ama"])The classic: two-sum
# Find two numbers that add to target\ndef two_sum(nums, target):\n seen = {}\n for i, n in enumerate(nums):\n needed = target - n\n if needed in seen:\n return [seen[needed], i]\n seen[n] = i\n return []\n\ntwo_sum([2, 7, 11, 15], 9) # [0, 1]Sets for dedup
def has_duplicates(nums):\n return len(nums) != len(set(nums))\n\n# intersection of two lists:\nset_a & set_b\n\n# only unique items:\nlist(set(items))Counting with Counter
from collections import Counter\n\ncounts = Counter("banana")\n# Counter({'a': 3, 'n': 2, 'b': 1})\n\ncounts.most_common(1) # [('a', 3)]Ordered structure
from collections import defaultdict, deque\n\n# defaultdict: auto-initialise missing keys\nword_map = defaultdict(list)\nword_map["a"].append(1)\n\n# deque: fast append/pop at both ends\ndq = deque([1, 2, 3])\ndq.appendleft(0)When to use which
| Need | Structure |
|---|---|
| Fast key lookup | dict / set |
| Count occurrences | Counter |
| Insert/remove both ends | deque |
| Key with default value | defaultdict |
Tip: When a problem says "find", "contains", "count" — reach for a dict or set first. It is usually the intended solution.
This is a free preview lesson
Enroll in the Problem Solving & Algorithms With Python to unlock every lesson, lesson PDF guides, quizzes and your certificate - and start creating your own pieces today.