Discussion 12: Data structures review and practice
Tue Nov 24 (B sections). A sections don't meet this week, so this is the B discussion, plus extra practice for anyone in A or anyone who couldn't make it.
We'll review the material since Midterm 2: traits and generics briefly, then the data structures week in depth.
- Part 1 is review, all of it from lecture
- Part 2 is practice on paper (no coding)
- Part 3 is two hand-coding practice problems
Part 1: Review
Traits and generics
A trait is a promise: any type that implements it has these methods.
trait Describe {
fn describe(&self) -> String; // what the method looks like
}
impl Describe for Player { // how one type keeps the promise
fn describe(&self) -> String {
format!("#{} {}", self.number, self.name)
}
}
#[derive(Debug, Clone, PartialEq)]asks the compiler to write theimplfor you- A generic function works for many types:
fn max<T: PartialOrd>(x: T, y: T) -> T T: PartialOrdis a trait bound: it means any typeT, as long as it can be comparedVec<Box<dyn Agent>>holds values of different types that all keep theAgentpromise. We can't know how big eachAgentis, so theVecholds a pointer to each one, and every element takes up the same space
What each collection requires of its type
The standard library's collections are generic, and each one puts a trait bound on what it stores.
| You write | The type needs | Because |
|---|---|---|
println!("{:?}", x) | Debug | It has to know how to print it |
v.sort() | Ord | Sorting compares pairs with cmp |
BinaryHeap<T> | Ord | It has to know which one is biggest |
HashSet<T>, and the keys of HashMap<K, V> | Eq + Hash | It hashes the key, then compares it to what's in the bucket |
BTreeSet<T>, and the keys of BTreeMap<K, V> | Ord | It keeps the keys in sorted order |
When the compiler says "the trait bound Striker: Ord is not satisfied", it means a method you're using on a Striker requires Striker to have the Ord trait but you haven't implemented it yet. Typically you can fix it by adding the trait mentioned to the derive line.
Derived Ord compares field by field, in the order the fields are declared. (To get a custom order you need to implement a cmp yourself.)
Which structure?
| Need | Use | Under the hood |
|---|---|---|
| Pop the newest | Vec | One block |
| Pop the oldest | VecDeque | One block, a head, % cap |
| Pop the biggest | BinaryHeap | One block, (i - 1) / 2 |
| Is this here? | HashSet | One block of buckets, hash % buckets |
| Look it up by key | HashMap | The same, with a value next to each key |
| Keep it sorted while it changes | A binary search tree, BTreeSet | One block per node, joined by pointers |
The first five are a Vec-shaped block on the heap plus some arithmetic. The binary search tree is the one with a different shape.
What each one costs
| Structure | Operation | Cost |
|---|---|---|
Vec | v[i], push(x), pop() | O(1) |
insert(0, x), remove(0), contains(&x) | O(n) | |
VecDeque | push_back, pop_front, push_front, pop_back | O(1) |
BinaryHeap | peek() | O(1) |
push(x), pop() | O(log n) | |
HashSet, HashMap | contains, get, insert, remove | O(1) average |
| Search tree | search, insert | O(height) |
O(height) is O(log n) when the tree is bushy and O(n) when it has turned into a chain.
Hash tables
A lookup is three steps, however many keys are stored:
- Hash the key to get a number
- Modulo by the number of buckets to get a bucket index
- Compare the key with what's in that bucket
hash("Alice") % 8 = 63350368 % 8 = 0
hash("Bob") % 8 = 66965 % 8 = 5
[0] [1] [2] [3] [4] [5] [6] [7]
Alice Bob
- Collision: the bucket's taken by a different key. Look in the next one, and keep going until you find the key or hit an empty bucket
- Growing: when it's getting close to full the bucket array doubles, and every key is re-hashed, because the modulo step changed (eg
% 8became% 16) - The order you get when you loop over a
HashSetor aHashMapis whatever order the buckets are in. It's effectively random.
Binary heaps
A max-heap is a complete binary tree where every parent is >= its children. Complete means no gaps, so the rows fit end to end in a Vec.
42
/ \
30 20 Vec: [42, 30, 20, 10, 25, 15, 8]
/ \ / \ Index: 0 1 2 3 4 5 6
10 25 15 8
- Parent of index
i:(i - 1) / 2. Children ofi:2 * i + 1and2 * i + 2 - Push: put the new value at the end, then bubble up. Swap with the parent while it's bigger than its parent
- Pop: take the root, move the last value into the root's spot, then bubble down. Swap with the larger child while a child is bigger
- One swap per row, about log n rows, so both are O(log n)
- Only parent and child are ordered. Siblings can be in any order, and the
Vecusually isn't sorted
VecDeque
One block, used as a ring. head is the slot holding the front, and len counts the elements.
slot: 0 1 2 3
┌─────┬─────┬─────┬─────┐
│ 50 │ 20 │ 30 │ 40 │ head: 1 len: 4
└─────┴─────┴─────┴─────┘
▲
head prints [20, 30, 40, 50]
- Element
iof the queue is at slot(head + i) % cap push_back: write at slot(head + len) % cap, thenlen + 1pop_front: take what's athead, thenheadmoves forward one slot andlen - 1push_front:headmoves back one slot and the value goes there. Back from slot 0 wraps to the last slotpop_back: take the last element,len - 1.headstays put- Nothing ever shifts, so all four are O(1). When the ring is full, it doubles the way a
Vecdoes (and unwraps/resets the ring)
Lists and trees
A node that holds another node needs a pointer, and the pointer is optional so the structure can end, which means we need both Option and Box:
struct Node { // a linked list
value: i32,
next: Option<Box<Node>>,
}
struct Node { // a binary tree
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
- Every
Box::newis its own block on the heap - A recursive type gets a recursive function:
Noneis the base case,Somerecurses
fn len(list: &Option<Box<Node>>) -> usize {
match list {
None => 0, // the end: nothing here
Some(node) => 1 + len(&node.next), // this one, plus the rest
}
}
Search trees
The BST property, at every node: everything in the left subtree is smaller, everything in the right subtree is bigger.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
- Search: compare with the node. Smaller, go left. Bigger, go right. Stop when you find it or fall off the bottom
- Insert: search for the value. The spot where the search falls off is where the new leaf goes
- In order: left subtree, then the node, then the right subtree gives the values sorted
- One comparison per row, so search and insert are O(height)
- Insert values in sorted order and every one goes right. The tree is a chain, and O(height) is O(n)
Two kinds of tree
BinaryHeap | Search tree | |
|---|---|---|
| The rule | Parent >= both children | Left < node < right, for whole subtrees |
| Shape | Complete, no gaps | Any (binary) shape |
| Memory | One block | One block per node |
| Find a child | Arithmetic, 2i + 1 | Follow a pointer |
| Biggest | peek, O(1) | Keep going right, O(height) |
Is x in here? | O(n), look at everything | O(height) |
| Insert | O(log n), bubble up | O(height), fill the hole |
| Everything in order | Sort it, O(n log n) | Left, node, right: O(n) |
Part 2: Practice on paper
No code to write in this part. Draw, trace, and explain.
Problem 1: what's the compiler asking for?
struct Song { title: String, plays: u32 }
For each line, name the trait or traits Song needs before it compiles, if any.
println!("{:?}", song);if song_a == song_b { ... }playlist.sort();whereplaylistis aVec<Song>seen.insert(song);whereseenis aHashSet<Song>heap.push(song);whereheapis aBinaryHeap<Song>queue.push_back(song);wherequeueis aVecDeque<Song>
Follow-up. We derive everything BinaryHeap<Song> needs, push "Yesterday" (20 plays), "Dreams" (27), and "Imagine" (24), then pop once. Which song comes out, and why?
Problem 2: build a hash table
The keys are jersey numbers. The hash function is trivial: hash(n) = n. The table has 8 buckets, so the bucket index is n % 8. On a collision, look in the next bucket, and past bucket 7 comes bucket 0.
Insert these, in this order: 23, 10, 15, 4, 31, 42
[0] [1] [2] [3] [4] [5] [6] [7]
- Fill in the table.
contains(&31): which buckets does it look in, in order?contains(&39): which buckets does it look in, and how does it know to stop?- Three of the six keys wanted the same bucket. Which property of a good hash function is this one missing?
- The table doubles to 16 buckets. Re-place the six keys in the same order. How many of them end up in a different bucket, compared with before?
Problem 3: hashing, short answers
- You print a
HashSetof team names, run the program again, and the names come out in a different order. Why? What would you do to print them alphabetically? winsis aHashMap<String, u32>with no entry for "The Ducks". What doeswins.get("The Ducks")give you? What doeswins["The Ducks"]do?- A loop calls
roster.contains(&name)once for each of 2,000 names, androsteris aVecof 50,000 names. Roughly how many comparisons is that in the worst case? How many lookups ifrosteris aHashSet?
Problem 4: read the Vec
Each of these is the Vec inside something that claims to be a max-heap. Draw each one as a tree and say whether it's a valid max-heap. If it isn't, name the parent and child that break the rule.
a. [88, 70, 65, 40, 52, 30, 61]
b. [50, 45, 48, 20, 46, 10, 47]
c. [10, 9, 8, 7, 6, 5, 4]
- Valid or not, for each?
- Is a
Vecsorted from biggest to smallest always a valid max-heap? Is a valid max-heap always sorted? - In a max-heap of n values, where can the smallest value be? What's the complexity of finding it?
Problem 5: push, then pop
Start from heap a in Problem 4:
- Push 75. Draw the tree and write the
Vecafter the swaps. How many swaps? - Now pop. What comes out? Draw the tree and write the
Vecafter the swaps. - In step 2, the value that moved to the root had two children bigger than it. Which one did you swap with, and what would happen if you went the other way?
Problem 6: trace a ring
A VecDeque<i32> called line with capacity 5, starting empty with head at slot 0:
push_back(3), push_back(8), push_back(5)
push_front(1)
pop_back()
push_front(6)
push_back(9)
- Draw the block after every line, with
headandlennext to it. - What does
println!("{:?}", line)print at the end? - Which slot holds the front? Which slot holds the back?
line[2]is which slot, and which value?- The ring is now full. What happens on the next
push_back(4)?
Problem 7: grow a search tree
Start from an empty binary search tree and insert these, in this order: 20, 9, 31, 4, 15, 26, 42, 12
- Draw the tree.
contains(&tree, 15): which nodes does it visit, and what comes back?contains(&tree, 28): which nodes does it visit, and what comes back?- Insert 28. Where does it go?
- Read the tree in order: left subtree, node, right subtree. What do you get?
- How many blocks are on the heap now? What would be on the stack?
- Say the same nine values went in smallest to biggest. What's the height of that tree, and what does a search cost?
Problem 8: which structure?
For each one, pick Vec, VecDeque, BinaryHeap, HashSet, HashMap, or a search tree (BTreeSet or BTreeMap). Say why in a few words, and name the trait the stored type or key needs, if any.
- A music app's "up next" list: songs play in the order you added them, and "play next" cuts one in at the front.
- Matchmaking for an online game: players join the waiting room all the time, and the highest-rated one waiting always gets matched first.
- From a season's list of goal events, find how many goals each player scored. (This one's trickier - think about how you'd do it by hand first.)
- The discard pile in a card game (you can only ever take the top card).
- Online Scrabble checks each word you play against a dictionary of 200,000 words.
- A leaderboard of players by rating that changes all day, and has to answer "everyone rated between 1500 and 1600" quickly.
Problem 9: costs, from memory
Cover the cost table in Part 1 and fill this in. n is the number of elements stored.
| Operation | Cost | Why, in a few words |
|---|---|---|
Vec: remove(0) | ||
Vec: contains(&x) | ||
VecDeque: pop_front() | ||
BinaryHeap: peek() | ||
BinaryHeap: push(x) | ||
HashSet: contains(&x) | ||
| Search tree, bushy: search | ||
| Search tree, built from sorted input: search | ||
BinaryHeap: "is x in here?" |
Part 3: Hand-coding
Focus on the overall shape rather than the & or * details.
Problem 10: the first repeat
A league needs every jersey number to be unique. Write first_repeat, which walks a slice of jersey numbers and returns the first number that shows up for a second time, or None if every number is different.
use std::collections::HashSet;
fn first_repeat(numbers: &[u32]) -> Option<u32> {
// your code here
}
fn main() {
println!("{:?}", first_repeat(&[23, 10, 7, 10, 23])); // Some(10)
println!("{:?}", first_repeat(&[23, 10, 7])); // None
}
The methods you need:
| Method | What it does |
|---|---|
HashSet::new() | An empty set |
set.insert(x) | Adds x to the set |
set.contains(&x) | true if x is in the set |
Follow-up.
- What's the Big-O of your function, for n numbers?
- What would the Big-O be if
seenwere aVecand you calledseen.contains(&x)?
Problem 11: how tall is the tree?
Here's the tree node from lecture, and len for a linked list. Write height for the tree: the number of rows. An empty tree has height 0, and a tree with one node has height 1.
struct Node {
value: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
// For reference: the length of a linked list, whose node has one `next`
fn len(list: &Option<Box<ListNode>>) -> usize {
match list {
None => 0,
Some(node) => 1 + len(&node.next),
}
}
fn height(tree: &Option<Box<Node>>) -> usize {
// your code here
}
Follow-up.
- What does
heightreturn for the tree you drew in Problem 7, after inserting 28? - What's the Big-O of
height, for n nodes? Can it skip a subtree the waycontainsdoes?