BST vs Hash Map Trade-offs for Ordered Data in DSA Typescript - Complexity Comparison
When choosing between a Binary Search Tree (BST) and a Hash Map, it is important to understand how their time costs grow with data size.
We want to see which structure works faster for searching, inserting, and keeping data in order.
Analyze the time complexity of these operations on BST and Hash Map.
// BST insert and search
function bstInsert(node: TreeNode | null, val: number): TreeNode {
if (!node) return new TreeNode(val);
if (val < node.val) node.left = bstInsert(node.left, val);
else node.right = bstInsert(node.right, val);
return node;
}
// Hash Map insert and search
const map = new Map();
const key = 1; // example key
const value = "example"; // example value
map.set(key, value);
const found = map.get(key);
The BST keeps data sorted and allows ordered traversal. The Hash Map stores data with fast access but no order.
- Primary operation: BST uses recursion to traverse nodes; Hash Map uses direct key access.
- How many times: BST may visit nodes along a path up to tree height; Hash Map accesses happen once per operation.
As data grows, BST operations depend on tree height; Hash Map operations depend on hashing efficiency.
| Input Size (n) | BST Operations (approx.) | Hash Map Operations (approx.) |
|---|---|---|
| 10 | Up to 4 steps (height ~ log 10) | 1 step (direct access) |
| 100 | Up to 7 steps (height ~ log 100) | 1 step (direct access) |
| 1000 | Up to 10 steps (height ~ log 1000) | 1 step (direct access) |
Pattern observation: BST steps grow slowly with input size; Hash Map steps stay almost constant.
Time Complexity: O(log n) for BST (average), O(1) for Hash Map (average)
BST operations take longer as data grows but keep order; Hash Map operations stay fast but lose order.
[X] Wrong: "Hash Maps always beat BSTs because they are faster for all operations."
[OK] Correct: Hash Maps do not keep data sorted, so they cannot do ordered tasks efficiently. Also, worst-case Hash Map operations can be slower if hashing is poor.
Understanding these trade-offs shows you can pick the right tool for the job, a key skill in coding interviews and real projects.
"What if the BST becomes unbalanced and looks like a linked list? How would the time complexity change?"
Practice
Solution
Step 1: Understand the requirement for sorted order and range queries
Maintaining sorted order and performing range queries require a data structure that keeps elements ordered.Step 2: Compare BST and Hash Map capabilities
BST keeps elements sorted and supports efficient range queries, while Hash Map does not maintain order.Final Answer:
Binary Search Tree (BST) -> Option AQuick Check:
Sorted order + range queries = BST [OK]
- Thinking Hash Map maintains order
- Confusing range queries with simple lookups
- Assuming Stack or Queue can maintain sorted data
Solution
Step 1: Identify the correct TypeScript Map declaration
TypeScript uses Map for hash maps, where K is key type and V is value type.Step 2: Check each option's syntax
const map: Map = new Map(); correctly declares a Map with string keys and number values. const map: HashMap = new HashMap(); uses a non-existent HashMap type. const map: Map = new Map(); swaps key and value types. const map: Object = {}; uses Object incorrectly.Final Answer:
const map: Map<string, number> = new Map(); -> Option DQuick Check:
Map<string, number> syntax correct [OK]
- Using non-existent HashMap type
- Swapping key and value types
- Using plain Object without type safety
class Node {
value: number;
left: Node | null = null;
right: Node | null = null;
constructor(value: number) { this.value = value; }
}
class BST {
root: Node | null = null;
insert(value: number) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return;
}
let current = this.root;
while (true) {
if (value < current.value) {
if (!current.left) {
current.left = newNode;
break;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
break;
}
current = current.right;
}
}
}
inorder(node: Node | null, result: number[]) {
if (!node) return;
this.inorder(node.left, result);
result.push(node.value);
this.inorder(node.right, result);
}
}
const bst = new BST();
bst.insert(3);
bst.insert(1);
bst.insert(4);
const map = new Map();
map.set(3, 'three');
map.set(1, 'one');
map.set(4, 'four');
const bstResult: number[] = [];
bst.inorder(bst.root, bstResult);
console.log(bstResult);
console.log(Array.from(map.keys()));
What will be the output?Solution
Step 1: Trace BST inorder traversal output
Inorder traversal visits nodes in ascending order: 1, 3, 4.Step 2: Trace Map keys insertion order
Map keys are iterated in insertion order: 3, 1, 4.Final Answer:
[1, 3, 4] [3, 1, 4] -> Option AQuick Check:
BST inorder sorted, Map keys insertion order [OK]
- Assuming Map keys are sorted
- Confusing preorder with inorder traversal
- Expecting Map keys to be sorted automatically
class BSTNode {
value: number;
left: BSTNode | null = null;
right: BSTNode | null = null;
constructor(value: number) { this.value = value; }
}
class BST {
root: BSTNode | null = null;
insert(value: number) {
const newNode = new BSTNode(value);
if (!this.root) {
this.root = newNode;
return;
}
let current = this.root;
while (current) {
if (value < current.value) {
current = current.left!;
} else {
current = current.right!;
}
}
}
}
const bst = new BST();
bst.insert(5);
bst.insert(3);
const map = new Map();
map.set(5, 'five');
map.set(3, 'three');Solution
Step 1: Analyze BST insert method loop
The loop moves current to left or right child but never assigns newNode to any child, so tree structure is not updated.Step 2: Understand consequences of missing link
Without linking newNode, the loop continues infinitely or tries to access null with non-null assertion, causing error.Final Answer:
The insert method does not link new nodes to the tree, causing infinite loop or error. -> Option CQuick Check:
Missing child assignment causes error [OK]
- Ignoring the need to assign newNode to left/right
- Thinking Map keys must be strings
- Assuming parent pointer is mandatory
Solution
Step 1: Identify requirements for sorted retrieval and fast lookup
Sorted retrieval by score needs a structure that keeps order, fast lookup by user ID needs quick key access.Step 2: Evaluate data structure combinations
Hash Map gives O(1) lookup by user ID. Balanced BST keeps scores sorted and can store user IDs. Combining both meets both needs efficiently.Step 3: Reject other options
Only Hash Map lacks sorted order. Only BST with user ID key sorts by ID, not score. Array sorting is costly on updates.Final Answer:
Use a Hash Map for user ID to score and a Balanced BST for scores with user IDs -> Option BQuick Check:
Combine Hash Map + BST for lookup + sorted order [OK]
- Using only one structure and missing one requirement
- Sorting array repeatedly on updates
- Using BST keyed by user ID instead of score
Ready to prove it?
Pass the test and this pattern moves unknown
