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.