Hash Table supports following operations in Θ(1) time.
So Hash Table seems to beating BST in all common operations. When should we prefer BST over Hash Tables, what are advantages. Following are some important points in favor of BSTs.
- We can get all keys in sorted order by just doing Inorder Traversal of BST. This is not a natural operation in Hash Tables and requires extra efforts.
- Doing order statistics, finding closest lower and greater elements, doing range queries are easy to do with BSTs. Like sorting, these operations are not a natural operation with Hash Tables.
- BSTs are easy to implement compared to hashing, we can easily implement our own customized BST. To implement Hashing, we generally rely on libraries provided by programming languages.
- With Self-Balancing BSTs, all operations are guaranteed to work in O(Logn) time. But with Hashing, Θ(1) is average time and some particular operations may be costly, especially when table resizing happens.
This article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- What are Hash Functions and How to choose a good Hash Function?
- Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
- Implementing our Own Hash Table with Separate Chaining in Java
- Hash Table vs STL Map
- Implementing own Hash Table with Open Addressing Linear Probing in C++
- Why is Binary Heap Preferred over BST for Priority Queue?
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST
- Sort elements by frequency | Set 4 (Efficient approach using hash)
- Sorting using trivial hash function
- MD5 hash in Java
- Hash Function for String data in C#
- Cryptographic Hash Function in Java
- String hashing using Polynomial rolling hash function
- Graph representations using set and hash
- Sum of f(a[i], a[j]) over all pairs in an array of n integers
- A program to check if a binary tree is BST or not