skip to content

VecDeque and BinaryHeap

VecDeque is a ring buffer for both ends, BinaryHeap a max-heap, and LinkedList is rarely the answer. Interviewers ask how to get a min-heap and when a deque fits.

on this pageshow

questions

5

In Rust, which std collection fits a sliding-window rate counter that appends new timestamps and expires old ones, and which methods do the work?

level: juniorimportance: must knowfreq 62%

answer

  1. queue, not a stack
  2. both ends, one allocation
  3. peek before you remove
  4. front, pop_front, push_back

basics

~10 s

Use std::collections::VecDeque: push_back each new timestamp, then pop_front while front() is older than the window. Both ends are amortised O(1), unlike Vec::remove(0), which shifts every remaining element.

solid answer

~40 s

A rate counter is a FIFO queue: hits join at one end and expire at the other. `VecDeque<T>` is std's growable ring buffer, so `push_back` and `pop_front` are amortised O(1) and never shift elements. `front()` returns `Option<&T>` so you can compare the oldest timestamp before removing it, and `pop_front()` returns `Option<T>`, `None` when empty. The expire step is `while let Some(&t) = q.front() { if now - t < window { break } q.pop_front(); }`, or since Rust 1.93 `while q.pop_front_if(|t| now - *t >= window).is_some() {}`. A `Vec` would need `remove(0)`, which shifts every remaining element. `VecDeque` also indexes in O(1) and iterates oldest to newest.

code

rust · 33 lines
rust
use std::collections::VecDeque;

/// Sliding-window rate counter: at most `limit` hits per `window_ms`.
struct RateCounter {
    window_ms: u64,
    limit: usize,
    hits: VecDeque<u64>, // timestamps in ms, oldest at the front
}

impl RateCounter {
    fn allow(&mut self, now_ms: u64) -> bool {
        // Expire timestamps that fell out of the window.
        while let Some(&oldest) = self.hits.front() {
            if now_ms - oldest < self.window_ms {
                break;
            }
            self.hits.pop_front();
        }
        if self.hits.len() < self.limit {
            self.hits.push_back(now_ms);
            true
        } else {
            false
        }
    }
}

fn main() {
    let mut rc = RateCounter { window_ms: 1000, limit: 3, hits: VecDeque::new() };
    for t in [0, 100, 200, 300, 1050, 1150] {
        println!("t={t:>4} allowed={}", rc.allow(t));
    }
}

go deeper

for a junior

Name VecDeque and the queue pair push_back and pop_front, and say pop_front returns an Option rather than panicking on an empty deque.

for a middle

Explain the ring buffer: a head index that advances on pop_front, wrap-around at the end of the allocation, and amortised O(1) growth. Contrast with Vec::remove(0) shifting every element.

for a senior

Mention the underflow trap on u64 timestamps, rejecting before pushing to bound memory per client, and pop_front_if from Rust 1.93 as the cleaner expire loop.

for a principal

Treat the per-key deque as a memory budget: a limit of N hits costs N timestamps per active key, so the window and limit set the counter's footprint across all clients.

## The shape of the problem A **sliding-window rate counter** answers one question per request: how many hits arrived in the last `window` milliseconds? The usual design stores one timestamp per accepted hit. Every new hit is appended at the **newest** end; before deciding, the counter throws away every timestamp that has fallen out of the window, and those always sit at the **oldest** end. That is a **FIFO queue**: items enter at the back and leave at the front, in the order they arrived. In Rust the std type built for this is `std::collections::VecDeque<T>`, a **double-ended queue implemented with a growable ring buffer**. Its own documentation names the default queue usage: `push_back` to add and `pop_front` to remove. ## What a ring buffer buys you A `VecDeque` owns one heap allocation, like a `Vec`, plus a `head` index and a length. The logical first element lives at `buf[head]`, and the sequence may **wrap around** the end of the allocation and continue at slot 0. Consequences: - Removing from the front just advances `head`; nothing is shifted. - Adding at either end writes into a free slot next to the current run. - When the buffer is full, it grows by reallocating, so pushes are **amortised O(1)**, not O(1) on every call. - Indexing with `q[i]` or `q.get(i)` is O(1), because the index is translated through `head`. ## The methods that do the work | Method | Returns | Cost or note | |---|---|---| | `push_back(t)` | `()` | amortised O(1) | | `front()` | `Option<&T>` | O(1) | | `pop_front()` | `Option<T>`, `None` if empty | amortised O(1) | | `pop_front_if(pred)` | `Option<T>` | stable since Rust 1.93 | | `len()` | `usize` | O(1) | `front()` peeks at the oldest timestamp without removing it, which is exactly what the expire step needs: look, compare, and only then remove. ## Writing the expire loop The classic loop, valid on every Rust release: ```rust while let Some(&oldest) = hits.front() { if now_ms - oldest < window_ms { break; } hits.pop_front(); } ``` Since **Rust 1.93**, `VecDeque::pop_front_if` takes a predicate (`FnOnce(&mut T) -> bool`), removes and returns the front element only when the predicate says yes, and returns `None` when it says no or the deque is empty. The loop collapses to one line: ```rust while hits.pop_front_if(|t| now_ms - *t >= window_ms).is_some() {} ``` A full `allow` call then runs in three steps: 1. Expire every front timestamp older than the window. 2. Compare `hits.len()` with the limit. 3. If under the limit, `push_back(now_ms)` and accept; otherwise reject. ## Why not a Vec, or a LinkedList - **`Vec::remove(0)`** shifts every remaining element one slot left, so each expiry costs O(n). With thousands of timestamps per key and a hot path, that is real CPU. - **Reversing a Vec** so the oldest sits at the end makes expiry cheap but moves the cost to inserting at the front. - **`LinkedList`** also has O(1) operations at both ends, but pays one heap allocation per timestamp and walks scattered memory; std itself notes that `Vec` or `VecDeque` is almost always the better choice. ## Edge cases worth naming - `now_ms - oldest` on `u64` panics on underflow in a debug build and wraps in a release build if a timestamp ever runs ahead of `now_ms`; `saturating_sub` makes the arithmetic total. - For a strict cap on memory, check the limit before `push_back`, as above, so the deque never holds more than `limit` entries. - Iterating a `VecDeque` goes front to back, so `hits.iter()` lists timestamps oldest first — handy for debugging. ## Choosing the element type The deque does not care what it stores, so the timestamp type is a separate decision: - **`u64` milliseconds** from a clock you pass in keeps the counter pure and trivially testable, as in the example. - **`std::time::Instant`** reads the monotonic clock directly and is immune to wall-clock jumps; compare with `now.duration_since(oldest) < window`. - **One counter per key** usually lives in a `HashMap<Key, VecDeque<u64>>`; the deque is the per-key part, the map is a separate subject. Whichever you pick, the queue discipline stays the same: oldest at the front, newest at the back, and the expire step only ever looks at `front()`.

  • Why compare with front() before calling pop_front(), instead of popping and pushing back?
    Popping first removes the timestamp even when it is still inside the window, and putting it back with `push_front` is extra work and easy to get wrong. `front()` returns `Option<&T>`, a borrow you can inspect for free, so the loop only removes what has really expired. Since Rust 1.93, `pop_front_if` packages the same look-then-remove step in one call.
  • How would you cap the counter's memory so one noisy client cannot grow its deque without bound?
    Check `len()` against the limit before `push_back` and reject instead of storing, so the deque never holds more than `limit` timestamps. `VecDeque::with_capacity(limit)` preallocates that much space up front. If you keep the newest N samples instead of rejecting, `truncate` keeps the front N, while `retain_back(n)`, stable since Rust 1.99, keeps the last N.

  • Use a Vec and call remove(0) to expire the oldest timestamp.
  • pop_front panics when the deque is empty.
  • VecDeque is a linked list, so indexing it is O(n).
  • push_back is O(1) on every single call, with no reallocation ever.
  • A BinaryHeap is needed because timestamps must be sorted.

Assumes Rust 1.99; VecDeque::pop_front_if and pop_back_if are stable since Rust 1.93, the front()/pop_front() loop works on every release.

open as a page

Rust's std::collections::BinaryHeap always pops the largest element; how do you make a job scheduler pop the earliest deadline first?

level: middleimportance: must knowfreq 58%

basics

~10 s

Wrap each entry in std::cmp::Reverse, as in heap.push(Reverse((deadline, id))). Reverse flips Ord, so BinaryHeap's max-heap pops the smallest deadline first; an Ord impl that compares backwards also works.

open as a page

Why is std::collections::LinkedList rarely the right choice in Rust, even for a queue that removes items from the middle?

level: middleimportance: should knowfreq 40%

basics

~20 s

LinkedList allocates a node per element and walks scattered memory, and std's docs say Vec or VecDeque is almost always better. On stable Rust its cursor and remove-at methods are unstable, so middle removal walks the list anyway.

open as a page

Why does calling `sort()` on a Rust VecDeque fail to compile, and what do `as_slices` and `make_contiguous` give you instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A VecDeque's elements can wrap past the end of its buffer, so it cannot deref to one slice and has no sort method (E0599). as_slices returns the two halves; make_contiguous rearranges them in place into one &mut [T].

open as a page

How does Rust's BinaryHeap::peek_mut let you change the top element in place, and when is the heap invariant restored?

level: seniorimportance: should knowfreq 30%

basics

~20 s

peek_mut returns a PeekMut guard that derefs to the top element. If you write through it, the guard's Drop sifts that element down, so the heap is repaired once, when the guard goes out of scope.

open as a page