More Collections: VecDeque, BTreeMap & BinaryHeap

Beyond Vec and HashMap, Rust's standard library ships specialized collections — a double-ended queue, an ordered map and set, and a priority heap — each tuned for a job those two cannot do efficiently.

Learn More Collections: VecDeque, BTreeMap & BinaryHeap in our free Rust course — a beginner-friendly interactive lesson with worked examples, a practice…

Part of the free Rust course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

In this lesson you'll learn when to reach for VecDeque , BTreeMap , BinaryHeap , and the set types — and why picking the right container makes your code both faster and clearer.

What You'll Learn in This Lesson

1️⃣ VecDeque — A Double-Ended Queue

A VecDeque<T> is a growable ring buffer that supports fast insertion and removal at both ends. With a plain Vec , removing from the front is O(n) because every other element must shift; VecDeque makes push_front , pop_front , push_back , and pop_back all O(1). The pop methods return Option<T> because the deque might be empty.

This is the collection of choice for a FIFO queue: push_back to enqueue and pop_front to dequeue. It is also ideal for breadth-first search and sliding-window algorithms.

2️⃣ BTreeMap & BTreeSet — Always Sorted

A BTreeMap<K, V> stores its entries in a balanced search tree, so iteration always visits keys in sorted order and lookups are O(log n). Unlike a HashMap , it supports range(..) queries and cheap access to the smallest and largest key. The set version, BTreeSet , is the same idea for unique values.

The range("B".."D") call returns only the entries whose keys fall in that half-open interval, already in order — something a HashMap simply cannot do without sorting everything first.

3️⃣ BinaryHeap — A Priority Queue

A BinaryHeap<T> is a priority queue: push is O(log n), and pop always removes the largest element (by Ord ). To make it a min-heap , wrap each value in std::cmp::Reverse , which flips the comparison so the smallest value comes out first.

Heaps shine in algorithms like Dijkstra's shortest path and "top-K" problems, where you repeatedly want the current best (or worst) item without keeping the whole collection sorted.

Sets round out the picture. A HashSet gives fast, unordered uniqueness and set algebra; a BTreeSet keeps the same unique values in sorted order.

Your turn. Fill in the blanks marked ___ , then run it.

Use a BinaryHeap plus Reverse to pull the three smallest numbers out of a list. Run it with cargo run and check the output.

📋 Quick Reference — Choosing a Collection

Practice quiz

What is a VecDeque best suited for?

  • Sorted keys
  • Hashing values
  • Fast push and pop at BOTH ends
  • Priority ordering

Answer: Fast push and pop at BOTH ends. VecDeque is a ring buffer giving O(1) operations at both the front and the back.

What does this print? let mut dq: VecDeque<i32> = VecDeque::new(); dq.push_back(1); dq.push_back(2); dq.push_front(0); println!("{:?}", dq);

push_front(0) places 0 ahead of 1 and 2, giving [0, 1, 2].

Why do VecDeque's pop_front/pop_back return Option<T>?

  • For sorting
  • To copy the value
  • Because they are async
  • Because the deque might be empty

Answer: Because the deque might be empty. Popping returns Option because there may be no element to remove.

How does a BTreeMap differ from a HashMap?

  • It is unordered
  • It keeps keys in sorted order and supports range queries
  • It cannot store values
  • It only allows integer keys

Answer: It keeps keys in sorted order and supports range queries. BTreeMap stores entries in sorted order (O(log n)) and supports range(..) queries.

What does this print? let mut s: BTreeMap<&str,i32> = BTreeMap::new(); s.insert("Charlie",70); s.insert("Alice",95); s.insert("Bob",82); for (k,_) in &s { print!("{} ", k); }

  • Alice Bob Charlie
  • Charlie Alice Bob
  • Bob Alice Charlie
  • Random order

Answer: Alice Bob Charlie. A BTreeMap iterates keys in ascending sorted order: Alice, Bob, Charlie.

Is Rust's BinaryHeap a max-heap or a min-heap by default?

  • Min-heap
  • Unordered
  • Max-heap (pop returns the largest)
  • Depends on insertion order

Answer: Max-heap (pop returns the largest). BinaryHeap is a max-heap; pop() and peek() return the largest element by Ord.

How do you turn a BinaryHeap into a min-heap?

  • Call .reverse()
  • Wrap each value in std::cmp::Reverse before pushing
  • Use a HashSet instead
  • Set a flag in new()

Answer: Wrap each value in std::cmp::Reverse before pushing. Wrapping values in Reverse flips the comparison so the smallest comes out first.

What does this print? let mut h = BinaryHeap::new(); for n in [3,1,4,1,5,9,2].iter() { h.push(*n); } print!("{:?}", h.pop());

  • Some(1)
  • Some(3)
  • Some(2)
  • Some(9)

Answer: Some(9). As a max-heap, the first pop returns the largest value, 9.

What does this print? let mut seen: HashSet<&str> = HashSet::new(); for w in ["red","green","red","blue","green"] { seen.insert(w); } println!("{}", seen.len());

  • 5
  • 3
  • 2
  • 4

Answer: 3. A HashSet ignores duplicates, leaving the three unique values red, green, blue.

When should you choose a BTreeSet over a HashSet?

  • When you need the fastest possible lookups
  • When duplicates are allowed
  • When you need elements kept in sorted order or range queries
  • When keys must be integers

Answer: When you need elements kept in sorted order or range queries. BTreeSet keeps unique values sorted and supports ordered iteration and ranges.