Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 the impl for you
  • A generic function works for many types: fn max<T: PartialOrd>(x: T, y: T) -> T
  • T: PartialOrd is a trait bound: it means any type T, as long as it can be compared
  • Vec<Box<dyn Agent>> holds values of different types that all keep the Agent promise. We can't know how big each Agent is, so the Vec holds 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 writeThe type needsBecause
println!("{:?}", x)DebugIt has to know how to print it
v.sort()OrdSorting compares pairs with cmp
BinaryHeap<T>OrdIt has to know which one is biggest
HashSet<T>, and the keys of HashMap<K, V>Eq + HashIt hashes the key, then compares it to what's in the bucket
BTreeSet<T>, and the keys of BTreeMap<K, V>OrdIt 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?

NeedUseUnder the hood
Pop the newestVecOne block
Pop the oldestVecDequeOne block, a head, % cap
Pop the biggestBinaryHeapOne block, (i - 1) / 2
Is this here?HashSetOne block of buckets, hash % buckets
Look it up by keyHashMapThe same, with a value next to each key
Keep it sorted while it changesA binary search tree, BTreeSetOne 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

StructureOperationCost
Vecv[i], push(x), pop()O(1)
insert(0, x), remove(0), contains(&x)O(n)
VecDequepush_back, pop_front, push_front, pop_backO(1)
BinaryHeappeek()O(1)
push(x), pop()O(log n)
HashSet, HashMapcontains, get, insert, removeO(1) average
Search treesearch, insertO(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:

  1. Hash the key to get a number
  2. Modulo by the number of buckets to get a bucket index
  3. 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 % 8 became % 16)
  • The order you get when you loop over a HashSet or a HashMap is 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 of i: 2 * i + 1 and 2 * 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 Vec usually 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 i of the queue is at slot (head + i) % cap
  • push_back: write at slot (head + len) % cap, then len + 1
  • pop_front: take what's at head, then head moves forward one slot and len - 1
  • push_front: head moves back one slot and the value goes there. Back from slot 0 wraps to the last slot
  • pop_back: take the last element, len - 1. head stays put
  • Nothing ever shifts, so all four are O(1). When the ring is full, it doubles the way a Vec does (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::new is its own block on the heap
  • A recursive type gets a recursive function: None is the base case, Some recurses
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

BinaryHeapSearch tree
The ruleParent >= both childrenLeft < node < right, for whole subtrees
ShapeComplete, no gapsAny (binary) shape
MemoryOne blockOne block per node
Find a childArithmetic, 2i + 1Follow a pointer
Biggestpeek, O(1)Keep going right, O(height)
Is x in here?O(n), look at everythingO(height)
InsertO(log n), bubble upO(height), fill the hole
Everything in orderSort 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.

  1. println!("{:?}", song);
  2. if song_a == song_b { ... }
  3. playlist.sort(); where playlist is a Vec<Song>
  4. seen.insert(song); where seen is a HashSet<Song>
  5. heap.push(song); where heap is a BinaryHeap<Song>
  6. queue.push_back(song); where queue is a VecDeque<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]

  1. Fill in the table.
  2. contains(&31): which buckets does it look in, in order?
  3. contains(&39): which buckets does it look in, and how does it know to stop?
  4. Three of the six keys wanted the same bucket. Which property of a good hash function is this one missing?
  5. 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

  1. You print a HashSet of team names, run the program again, and the names come out in a different order. Why? What would you do to print them alphabetically?
  2. wins is a HashMap<String, u32> with no entry for "The Ducks". What does wins.get("The Ducks") give you? What does wins["The Ducks"] do?
  3. A loop calls roster.contains(&name) once for each of 2,000 names, and roster is a Vec of 50,000 names. Roughly how many comparisons is that in the worst case? How many lookups if roster is a HashSet?

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]
  1. Valid or not, for each?
  2. Is a Vec sorted from biggest to smallest always a valid max-heap? Is a valid max-heap always sorted?
  3. 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:

  1. Push 75. Draw the tree and write the Vec after the swaps. How many swaps?
  2. Now pop. What comes out? Draw the tree and write the Vec after the swaps.
  3. 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)
  1. Draw the block after every line, with head and len next to it.
  2. What does println!("{:?}", line) print at the end?
  3. Which slot holds the front? Which slot holds the back?
  4. line[2] is which slot, and which value?
  5. 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

  1. Draw the tree.
  2. contains(&tree, 15): which nodes does it visit, and what comes back?
  3. contains(&tree, 28): which nodes does it visit, and what comes back?
  4. Insert 28. Where does it go?
  5. Read the tree in order: left subtree, node, right subtree. What do you get?
  6. How many blocks are on the heap now? What would be on the stack?
  7. 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.

  1. A music app's "up next" list: songs play in the order you added them, and "play next" cuts one in at the front.
  2. Matchmaking for an online game: players join the waiting room all the time, and the highest-rated one waiting always gets matched first.
  3. 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.)
  4. The discard pile in a card game (you can only ever take the top card).
  5. Online Scrabble checks each word you play against a dictionary of 200,000 words.
  6. 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.

OperationCostWhy, 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:

MethodWhat 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.

  1. What's the Big-O of your function, for n numbers?
  2. What would the Big-O be if seen were a Vec and you called seen.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.

  1. What does height return for the tree you drew in Problem 7, after inserting 28?
  2. What's the Big-O of height, for n nodes? Can it skip a subtree the way contains does?