Interval Tree — Stabbing Queries
Tutorial Video
Text description (accessibility)
This video demonstrates the "Interval Tree — Stabbing Queries" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Given a set of intervals [l, r] and a query point q, find all intervals that contain q (stabbing query). Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Given a set of intervals [l, r] and a query point q, find all intervals that contain q (stabbing query). Naive linear scan is O(n) per query. An interval tree answers stabbing queries in O(log n + k) where k is the number of reported intervals, after O(n log n) preprocessing. This enables efficient scheduling conflict detection (does event at time q overlap any existing booking?), genomic range queries (which genes cover position q?), and network packet classification (which firewall rules match this port range?). Interval trees are the data structure behind many calendar and scheduling applications.
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Tree structure | Option<Box<IntervalTree>> | Algebraic type with Leaf |
| Sorted intervals | Vec<(i64, i64)> | (int * int) list |
| Null handling | Option | Pattern match on Leaf |
| Build complexity | O(n log n) | Same |
| Query complexity | O(log n + k) | Same |
| Memory | Compact Vec tuples | GC-managed list nodes |
OCaml Approach
OCaml represents the interval tree with an algebraic type: type t = Leaf | Node of { center: int; left_sorted: interval list; right_sorted: interval list; left_child: t; right_child: t }. The stab q tree function pattern-matches on the tree structure. List.filter or binary search on sorted lists reports crossing intervals. OCaml's immutable default makes building the tree via let rec build natural. The List.sort and List.rev operations create the two sorted interval lists.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Interval Tree Stabbing
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
all_overlaps(l, r): find all intervals that overlap the query interval [l, r].(l, r), [l, r), (l, r], [l, r] all handled correctly.