When would you choose a hash map over a sorted array or balanced tree for storing key-value data, and what do you give up?
FoundationalHow to answer
What they’re really asking
Whether you understand the practical time/space trade-offs of common data structures rather than just memorizing Big-O tables.
Strong answer structure
Hash map gives average O(1) insert/lookup/delete, ideal when you need fast point lookups by key and don't care about order. You give up ordered iteration and range queries (a tree gives O(log n) ordered operations), worst-case can degrade to O(n) on bad hashing/collisions, and you pay memory overhead and rehashing cost on growth. Choose a tree/sorted structure when you need sorted traversal, range scans, or predictable worst-case bounds.
Likely follow-ups
- How does a hash map resize, and why is amortized O(1) still true despite occasional O(n) rehashes?
- What makes a good hash function, and what happens with a poor one?
- How would you implement an LRU cache using these structures?