WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Data Structures · question 10 of 120

When would you use a tree instead of a hash table?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

There are several scenarios where a tree is more advantageous than a hash table.

1. **Ordered Data**: Trees are commonly used with an ordering criterion. They allow relatively efficient insertions, deletions and lookups, which makes them suitable for situations where order matters. A tree-based data structure like a Binary Search Tree (BST) keeps its elements sorted in order, which facilitates operations like searching for an element in the tree: the average time complexity is O(log n). In contrast, while hash tables provide efficient searching capabilities, they do not maintain any order.

2. **Range Queries**: If an application involves a lot of range queries (e.g., find all numbers between x and y), trees are a better choice. This operation is extremely inefficient in a hash table. For example, you can do an in-order traversal of a BST pretty efficiently.

3. **Min/Max Lookup:** Tree structures like a Binary Heap can be used efficiently to model a priority queue, which provides quick operations to look for, insert, or delete from a collection of items based on priority. With a binary heap, you can find the min/max element in constant O(1) time. While hash tables offer efficient lookup, insert and delete operations, they do not provide a quick way to identify the minimum or maximum values.

4. **Duplicated Keys:** Trees can handle the duplication of keys efficiently. Suppose we talk about the BST, if you try to insert a duplicated key, it would go as left child (or right depending upon the rules you are following). In hash tables, duplicate keys aren’t allowed by default.

These are broad guidelines and the choice of data structure would depend on a variety of factors such as the nature of the problem, the specific requirements of the operation, and the characteristics of the input data.

Here’s an example of a Binary Search Tree:


         8
       /   \
      3     10
     / \      \
    1   6      14 
       /  \    / 
      4    7  13 

In this BST tree, the left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics