Sets & Maps
Hash tables power two of the most useful data structures in everyday programming: Sets and Maps.
A Set is like a bouncer at a club with a guest list — you can ask "Is this person on the list?" and get an instant yes or no. No duplicates allowed. A Map (also called a dictionary or hash map) is like a phone book — given a name (key) you get a phone number (value) immediately.
Python — dict and set
Python's built-in dict is a hash map. Python's set is basically a dict with no values, just keys. Both use open addressing with a custom probing strategy.
JavaScript — Map, Set, and plain objects
JS has three options and they are not equivalent:
Object— key-value store but keys must be strings/symbols; has prototype pollution risk; no guaranteed insertion-order before ES2015Map— keys can be any type; guaranteed insertion-order iteration; has.sizeproperty; preferred for algorithmic useSet— unique values of any type; iteration in insertion order
Rule of thumb: use Map/Set when your keys aren't simple strings, or when you need insertion-order iteration. Use a plain object when you know keys are strings and you want JSON-serializable output.
← → arrow keys to step · click elements to interact
Sets & Maps: Core Operations
Common interview patterns using Map/Set
Two Sum — store each number's index in a Map. For each new number check if the complement exists in \(O(1)\).
Contains Duplicate — add elements to a Set. If .add() would create a duplicate, the Set size stops growing — or just check has() before adding.
Group Anagrams — sort each word to get a canonical key ("eat" → "aet"), use that as a Map key, append the word to the list.
Ordered vs Unordered
Standard hash-based Maps/Sets are unordered — iteration order is not guaranteed to match insertion order (language-dependent). If you need sorted iteration, use a TreeMap (Java) or SortedDict (Python sortedcontainers), which use a balanced BST internally and give \(O(\log n)\) operations.