Which reason best explains why a Binary Search Tree (BST) is preferred over a Hash Map when you need to maintain data in order?
Think about how each data structure stores and accesses data.
BST stores data in a way that keeps keys sorted, so you can easily get ordered data by traversing it. Hash Maps do not maintain order.
Given the following data inserted in this order: 5, 3, 7 into a BST and a Hash Map, what is the output of an in-order traversal of the BST and iteration over the Hash Map?
const bst = new BST(); bst.insert(5); bst.insert(3); bst.insert(7); const hashMap = new Map(); hashMap.set(5, 'five'); hashMap.set(3, 'three'); hashMap.set(7, 'seven'); // Output BST in-order traversal keys // Output Hash Map keys iteration order
Remember how in-order traversal works and how Map preserves insertion order.
In-order traversal of BST visits nodes in ascending order: 3, 5, 7. Map iteration preserves insertion order: 5, 3, 7.
Consider this simplified BST insert code snippet. Why does it fail to keep the tree ordered?
class Node { constructor(public val: number, public left: Node | null = null, public right: Node | null = null) {} } class BST { root: Node | null = null; insert(val: number) { if (!this.root) { this.root = new Node(val); return; } let current = this.root; while (current) { if (val < current.val) { current.left = new Node(val); break; } else { current.right = new Node(val); break; } } } }
Look at how the left and right children are assigned inside the loop.
The code assigns new nodes directly to left or right child without checking if those children already exist, so it overwrites existing subtrees and breaks the BST property.
You need to frequently find all keys between two values (range queries) in a large dataset. Which data structure is best suited?
Think about which structure allows ordered traversal and efficient range filtering.
BST allows in-order traversal which visits keys in sorted order, making range queries efficient. Hash Maps and stacks do not maintain order, and arrays require sorting each time if modified.
Given the following operations, what is the final output of the BST in-order traversal and the Hash Map keys iteration?
const bst = new BST(); bst.insert(10); bst.insert(5); bst.insert(15); bst.insert(12); bst.insert(18); const hashMap = new Map(); hashMap.set(10, 'ten'); hashMap.set(5, 'five'); hashMap.set(15, 'fifteen'); hashMap.delete(5); hashMap.set(12, 'twelve'); hashMap.set(18, 'eighteen'); // Print BST in-order traversal keys // Print Hash Map keys iteration order
Remember that deleting a key from Map removes it from iteration, and BST in-order traversal is sorted.
BST in-order traversal visits nodes in ascending order: 5, 10, 12, 15, 18. Hash Map iteration preserves insertion order except deleted keys are removed, so keys are 10, 15, 12, 18.