Rust offers a neat function that groups adjacent elements of a Vec.
let v = vec![1, 2, 3, 4, 5];
for w in v.windows(2) {
println!("{:?}", w);
}
// [1, 2]
// [2, 3]
// [3, 4]
// [4, 5]
Other languages offer similar things: Ruby (each_cons), Kotlin (windowed), Scala (sliding), Python (pairwise for n=2). In the case of Rust, very aligned to its main goals, these windows are borrowed, so zero allocation.
It’s O(n) time.