HashSet - Rust By Example

Sets have 4 primary operations (all of the following calls return an iterator):

  • union: get all the unique elements in both sets.

  • difference: get all the elements that are in the first set but not the second.

  • intersection: get all the elements that are only in both sets.

  • symmetric_difference: get all the elements that are in one set or the other, but not both.

Question: Is HashSet O(1) and Vec O(n) in rust?

In Rust, the O(1) versus O(n) comparison between a HashSet and a Vec primarily refers to lookup operations, such as checking if a collection contains a specific element. While a HashSet provides O(1) average time complexity for lookups, a Vec requires O(n) time because it must perform a linear search.

OperationVec<T>HashSet<T>
Lookup (contains)O(n) 1O(1) average 12
Add ElementO(1) amortized (push) 3O(1) average (insert) 2
Remove ElementO(n) (remove), O(1) (pop/swap_remove) 3O(1) average (remove)

Lookup Performance

Checking if an element exists using contains() is where the O(n) vs O(1) difference is most prominent. A HashSet computes a hash to instantly find the element’s bucket, offering O(1) average lookup time regardless of the collection’s size. In contrast, a Vec must iterate through its elements one by one until a match is found, resulting in O(n) time complexity where the search time grows linearly with the number of elements.415

Insertion and Removal

Appending an element to a Vec using push() operates in amortized O(1) time, though occasional capacity reallocations can cause brief performance spikes. HashSet insertions are also O(1) on average, but the operation carries a higher “constant factor” because computing the hash and handling potential bucket collisions requires more CPU work than simply placing an item at the end of a vector. For removals, HashSet operates in O(1) average time, whereas removing an element from a specific index in a Vec using remove() is O(n) because it requires shifting all subsequent elements to fill the gap.354

Footnotes

  1. https://zenn.dev/iriko/articles/d06fdc5a3de863 2 3

  2. https://dev.to/alexmercedcoder/working-with-collections-in-rust-a-comprehensive-guide-3c9f 2

  3. https://oneuptime.com/blog/post/2026-02-01-rust-collections/view 2 3

  4. https://stackoverflow.com/questions/72877598/hashset-is-slower-than-bruteforce-in-rust 2

  5. https://nindalf.com/posts/optimising-rust/ 2