Choose a hash map when you only need lookups, inserts and deletes by key, and you want average constant time. Choose a balanced tree when you need ordering: range scans, nearest key, or iterating in sorted order, all in logarithmic time. Trees also give you predictable worst case behavior, while a hash map can degrade badly with poor hashing or stall on a resize at the wrong moment.
Why interviewers ask this
This is a proxy for whether you pick data structures on purpose or reach for a dictionary by reflex. The interviewer wants to hear that you connect the access pattern to the structure, that you know hash map performance is an average rather than a guarantee, and that you recognize when ordering, range queries or bounded worst case latency make a tree the right call.
How to structure your answer
- State the operations each structure is genuinely good at.
- Tie the choice to the access pattern in the question.
- Mention worst case behavior, not just the average.
- Give one example where you switched from one to the other.
Example answer
My default is a hash map, because most of the time I am doing point lookups by id and constant average time is hard to beat. The moment the requirement involves ordering, though, I switch. Anything like give me all events between two timestamps, or find the next key after this one, is a range query, and a hash map cannot do it without scanning everything. That wants a tree, or in practice a sorted structure with binary search. I also think about the tail. Hash lookups are constant on average, but a bad hash function or a rehash can spike, and inside a latency budget I care about that. On a leaderboard feature I built we started with a dictionary of user to score and then had to sort the whole thing on every read. Once we moved to a sorted set in Redis, reads became logarithmic and the endpoint stopped falling over at peak. Same data, different access pattern, different structure.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- What happens to a hash map when a lot of keys collide?
- How would you implement a least recently used cache?
- When is a trie a better fit than either one?
Related software engineer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions