HashMap and HashSet
A HashMap stores key -> value pairs with average O(1) lookup. A HashSet stores unique values. They solve a huge number of interview problems.
HashMap and HashSet give near-instant lookups, which turns many slow O(n²) solutions into O(n). Counting, finding duplicates and two-sum style problems are classic uses.
Example
Counting frequencies
Example
Two Sum in O(n)
Classic interview question: find two numbers that add up to a target. The HashMap remembers numbers we've seen:
Example
HashSet: duplicates
Example
HashMap order is not guaranteed - use
TreeMap (sorted) or LinkedHashMap (insertion order) when order matters. Keys you put in a HashMap must have correct equals and hashCode.Key points
- HashMap maps keys to values in O(1) average.
- HashSet stores unique values.
- TreeMap keeps keys sorted.
📝 Test yourself
1. Average time to look up a key in a HashMap?
2. Which map keeps keys sorted?
3. Fill in the method that returns a default when the key is missing:
stock.("ink", 0)
