TIL: Vec::swap_remove

Anarchy gives you O(1)


Today I came across Vec::swap_remove in Rust’s standard library for the first time. I guess I am one of today’s lucky 10 000.

If you don’t care about retaining the order of the elements in a Vec, and you’d like to remove an element at a specific index, you can use Vec::swap_remove to remove the element at that index by swapping it out for the last element. This is constant time (O(1)) instead of Vec::remove’s linear time (O(n)).