CS205 Data Structures
Use arrow keys or buttons to navigate
A map (dictionary / associative array) stores (key, value) pairs. Each key maps to exactly one value. Keys must be unique.
A map is about lookup by key. You don't ask "what's at position 3?" — you ask "what is the value for key "banana"?"
The abstract interface any map implementation must support:
put("apple",5) then put("apple",9) → only one "apple" entry with value 9. The old value 5 is replaced.
Three fundamental collection types — each organizes data differently.
| Feature | List | Set | Map |
|---|---|---|---|
| Access by | Index | Membership | Key |
| Duplicates | Allowed | No | Keys unique |
| Order | Yes | Depends | Depends |
| Use when | Ordered seq. | Uniqueness | Key lookup |
Which would you use?
Need to find items by position? → List. Need to check membership? → Set. Need to look up value by key? → Map.
Store entries in an unordered list — simple but slow
| Operation | Time | Why? |
|---|---|---|
| get(k) | O(n) | Linear scan |
| put(k,v) | O(n) | Search first |
| remove(k) | O(n) | Linear scan |
Without ordering, finding a key requires checking every entry. Even put() must search first to check if the key already exists.
For very small maps (< 20 entries), the simplicity and cache-friendliness outweigh the O(n) cost.
Keep entries sorted by key — binary search for O(log n) lookups
| Operation | Time |
|---|---|
| get(k) | O(log n) |
| put(k,v) existing | O(log n) |
| put(k,v) new | O(n) |
| remove(k) | O(n) |
Finding a key is O(log n) — much better! But inserting a new key still needs shifting to maintain sorted order → O(n).
To insert "cow" between "cat" and "dog", we must shift "dog" and "fish" right. Same shifting cost as ArrayList insertion.
A variation where one key maps to multiple values
One-to-many: student → courses, word → positions in text, vertex → neighbors (adjacency list).
Two cases: update existing key, or insert new entry
Even for insertion, put() must scan all entries to check if the key exists. This is why put() in an unsorted list is O(n), not O(1).
Return value: old value (update) or null (insert).
Search for a key and return its value, or null if absent
If get("grape") returns null — is the key absent, or does it exist with a null value? Use containsKey() to disambiguate:
Find entry by key, remove it, return old value
Since unsorted list has no required order, replace the removed entry with the last in O(1). Search is still O(n), but the removal step itself is O(1).
Does NOT work for sorted arrays — swapping breaks sorted order.
Keys in sorted order — enables range queries and ordered traversal
Unsorted map = tossing files in a box — fast to add, slow to find. Sorted map = alphabetized filing cabinet — slightly slower to insert, but fast lookup and browsing.
Keys must implement Comparable or you must provide a Comparator.
Two powerful map implementations ahead
Compute index directly from key via hash function. No search needed! Trade-off: no ordering, O(n) worst case from collisions.
O(log n) for all operations AND sorted order. Java's TreeMap = Red-Black BST.
| Implementation | get() | put() | remove() | Ordered? |
|---|---|---|---|---|
| Unsorted List | O(n) | O(n) | O(n) | No |
| Sorted Array | O(log n) | O(n) | O(n) | Yes |
| Hash Table | O(1) avg | O(1) avg | O(1) avg | No |
| Balanced BST | O(log n) | O(log n) | O(log n) | Yes |
Count occurrences of each word — a classic map use case
New word? Add a row with count 1. Seen again? Add a tally mark. The map is the tally sheet.
Predict the return values and final map state
Starting with an empty map, execute:
Find two numbers that add to a target — O(n) with a map
Store each number in a map as you go. For each new number, compute its complement (target − num) and check if it's already in the map. One pass = O(n) vs O(n²) brute force.
People enter a room one at a time, each with a number. Each asks: "Is someone here whose number + mine = target?" If yes — pair found! The map is the room's registry.
This word frequency counter has a subtle error
What happens when this code runs on "the cat the"?
freq.get("the") returns null. Java tries to unbox null to int for the + 1, causing a NullPointerException.freq.put(word, freq.getOrDefault(word, 0) + 1);containsKey() first (as shown in the original code).
HashMap, TreeMap, LinkedHashMap — different trade-offs
| Impl | Order | Ops | null keys? |
|---|---|---|---|
| HashMap | None | O(1) avg | Yes (1) |
| TreeMap | Sorted | O(log n) | No |
| LinkedHashMap | Insertion | O(1) avg | Yes (1) |
Fastest lookups? → HashMap
Sorted keys / ranges? → TreeMap
Insertion order (LRU cache)? → LinkedHashMap
HashMap iteration order is unpredictable and changes when entries are added/removed.
HashMap, TreeMap, or LinkedHashMap?
1. Count word frequencies in a large text file as fast as possible.
2. Store user settings and write them to a config file in the order they were added.
3. Implement an address book where contacts are always displayed alphabetically.
4. Find all students with IDs between 1000 and 2000.
1. HashMap — O(1) avg ops, no ordering needed for counting.
2. LinkedHashMap — preserves insertion order, so settings write in the order added.
3. TreeMap — keys automatically sorted alphabetically.
4. TreeMap — subMap(1000, 2001) gives all IDs in the range. HashMap can't do range queries.
Everything you need to know about maps in one slide
Lists are about ordering. Sets are about uniqueness. Maps are about association — connecting a key to its value. Maps are arguably the most widely used data structure in real-world programming.
Hash Tables — how to achieve O(1) average using hash functions and buckets.
3 questions — pick the best answer
Q1: What does put("x",5) return if "x" already has value 3?
Q2: Why is put() O(n) in an unsorted list map?
Q3: Which Java Map preserves insertion order?
What is printed?
Enter the 5 printed values (one per line):
Apply the map-based two-sum pattern
Given nums = [3, 1, 4, 1, 5, 9] and target = 10, trace the map-based two-sum algorithm.
At which index do we find the solution?
(i.e., what value of i triggers the "found" branch?)