What if you could find your data lightning fast and also see it neatly sorted without extra work?
BST vs Hash Map Trade-offs for Ordered Data in DSA Typescript - Why the Distinction Matters
Imagine you have a big phone book with names and numbers. You want to find a number quickly, but also want to see the names in alphabetical order. If you just flip pages randomly, it takes a long time to find what you want.
Looking up names one by one or scanning the whole list is slow and tiring. If you use a simple list, finding a name or sorting the list every time wastes time. Also, if you want to find the next name after a given one, it's hard without order.
Using a Binary Search Tree (BST) keeps names sorted as you add them, so you can find, add, or remove names quickly and also see them in order. A Hash Map finds names super fast but doesn't keep them sorted. Choosing between BST and Hash Map depends on whether you need order or just fast lookup.
const phoneBook = [['Alice', '123'], ['Bob', '456'], ['Charlie', '789']]; // To find 'Bob', scan each entry until found
class BSTNode { constructor(public key: string, public value: string, public left: BSTNode | null = null, public right: BSTNode | null = null) {} } // BST keeps keys sorted for quick ordered access
You can quickly find data and also get it in sorted order when needed, making your programs smarter and faster.
Online stores use BSTs to show products sorted by price or name, while using Hash Maps to quickly find product details by ID.
BST keeps data sorted for ordered access.
Hash Map offers faster lookup but no order.
Choosing depends on whether order or speed is more important.
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
