Skip to main content
All tracks
DSA in Python

Hash Tables

A hash table maps keys to values using a hash function. Python's dict and set are hash tables with O(1) average insert, lookup and delete.

Counting​

from collections import Counter

words = ["a", "b", "a", "c", "a"]
print(Counter(words).most_common(1)) # [('a', 3)]

Two Sum​

def two_sum(nums, target):
index = {} # value -> position
for i, x in enumerate(nums):
need = target - x
if need in index:
return [index[need], i]
index[x] = i
return [] # O(n) time, O(n) space

Grouping anagrams​

from collections import defaultdict

def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())

Good to know​

  • Keys must be hashable (int, str, tuple of hashables; not list).
  • Worst case is O(n) when many keys collide, but this is rare with a good hash.
  • A set is a dict without values: use it for membership and de-duplication.
Finished reading?

Mark it complete to track your progress across the docs.

Questions and discussion

Stuck on something here, or found a clearer way to explain it? Start a thread.

All discussions
  • Ask a question or share what helped
  • React to useful answers
  • Sign in with GitHub to post

Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.