BST vs Hash Map Trade-offs for Ordered Data in DSA Javascript - Complexity Comparison
We want to understand how fast different data structures work when we store and find data in order.
Which one is better for ordered data: a Binary Search Tree or a Hash Map?
Analyze the time complexity of these basic operations on BST and Hash Map.
// Insert and search in Binary Search Tree (BST)
function bstSearch(root, value) {
if (!root || root.value === value) return root;
if (value < root.value) return bstSearch(root.left, value);
else return bstSearch(root.right, value);
}
// Insert and search in Hash Map
const map = new Map();
map.set(key, value); // insert
map.get(key); // search
This code shows how we search in a BST using recursion and how we insert/search in a Hash Map.
Look at what repeats when we search or insert:
- Primary operation in BST: Comparing values and moving down one child node.
- How many times: Up to the height of the tree (number of levels).
- Primary operation in Hash Map: Computing a hash and accessing a bucket.
- How many times: Usually once, but sometimes more if collisions happen.
As we add more data (n):
| Input Size (n) | BST Operations (height) | Hash Map Operations |
|---|---|---|
| 10 | About 4 steps | Usually 1 step |
| 100 | About 7 steps | Usually 1 step |
| 1000 | About 10 steps | Usually 1 step |
BST steps grow slowly with input size (logarithmic), Hash Map steps stay almost the same.
Time Complexity: O(log n) for BST (balanced), O(1) average for Hash Map
BST takes more steps as data grows but keeps order; Hash Map is faster but does not keep order.
[X] Wrong: "Hash Maps always work in constant time no matter what."
[OK] Correct: Sometimes many keys hash to the same spot, making operations slower. Also, Hash Maps don't keep data sorted.
Knowing when to use BST or Hash Map shows you understand trade-offs between speed and order, a key skill in coding interviews.
What if we used a balanced BST like an AVL tree instead of a simple BST? How would the time complexity change?