📖 Scenario: Imagine you are managing a small library's book collection. You want to store book titles and their number of copies. Sometimes you need to find a book quickly by its title, and sometimes you want to see all books in alphabetical order.
🎯 Goal: You will create two data structures: a Binary Search Tree (BST) and a Hash Map (Dictionary). You will add the same books to both, then retrieve and print the books in alphabetical order using the BST, and demonstrate quick lookup using the Hash Map.
📋 What You'll Learn
Create a BST with book titles as keys and copies as values
Create a Hash Map (Dictionary) with the same book data
Implement an in-order traversal method to print BST books in alphabetical order
Show quick lookup of a book's copies using the Hash Map
💡 Why This Matters
🌍 Real World
Libraries, bookstores, and inventory systems often need to store and retrieve items quickly and sometimes in order. Choosing the right data structure helps balance speed and order.
💼 Career
Understanding BSTs and hash maps is essential for software developers working on databases, search engines, and any system requiring efficient data storage and retrieval.
Progress0 / 4 steps
1
Create the Book Data Dictionary
Create a Dictionary<string, int> called bookCopies with these exact entries: "The Hobbit": 5, "1984": 8, "Brave New World": 3, "Fahrenheit 451": 6, "Animal Farm": 7.
DSA C#
Hint
Use new Dictionary<string, int> { {"key", value}, ... } syntax to create the dictionary.
2
Create the BST Node Class and Insert Method
Add a class BSTNode with string Title, int Copies, BSTNode Left, and BSTNode Right fields. Then create a method Insert(BSTNode root, string title, int copies) that inserts a new node in the BST by title in alphabetical order.
DSA C#
Hint
Use recursion to insert nodes alphabetically by comparing titles.
3
Build the BST from the Dictionary
In Main, create a BSTNode root initialized to null. Then use a foreach loop with variables title and copies over bookCopies to insert each book into the BST using the Insert method.
DSA C#
Hint
Use a foreach loop to get each book and insert it into the BST.
4
Print BST In-Order and Lookup in Hash Map
Add a method InOrderPrint(BSTNode root) that prints each book title and copies in alphabetical order using in-order traversal. In Main, call InOrderPrint(root). Then print the number of copies for the book "1984" using bookCopies["1984"].
DSA C#
Hint
Use recursion for in-order traversal: left subtree, root, right subtree. Then print the copies from the dictionary.
Practice
(1/5)
1. Which data structure is best suited when you need to maintain data in sorted order and perform fast range queries?
easy
A. Binary Search Tree (BST)
B. Hash Map
C. Stack
D. Queue
Solution
Step 1: Understand the need for sorted data
Maintaining sorted order requires a data structure that keeps elements in order automatically.
Step 2: Compare BST and Hash Map for order
BST keeps elements sorted by design, while Hash Map does not maintain any order.
Final Answer:
Binary Search Tree (BST) -> Option A
Quick Check:
Sorted data needs BST [OK]
Hint: Sorted order needs BST, hash maps don't keep order [OK]
Common Mistakes:
Thinking hash maps keep data sorted
Confusing stack or queue with ordered structures
Assuming hash maps support range queries
2. Which of the following is the correct way to declare a HashMap in C# that maps integers to strings?
easy
A. Hashtable map = new Hashtable();
B. Dictionary map = new Dictionary();
C. Map map = new Map();
D. HashMap map = new HashMap();
Solution
Step 1: Identify C# collection for key-value pairs
C# uses Dictionary for hash map functionality.
Step 2: Check syntax correctness
Dictionary map = new Dictionary(); uses Dictionary with correct syntax; others are invalid or not C# standard.
Final Answer:
Dictionary map = new Dictionary(); -> Option B
Quick Check:
C# hash map = Dictionary [OK]
Hint: Use Dictionary for hash maps in C# [OK]
Common Mistakes:
Using Java's HashMap syntax in C#
Trying to use Map or Hashtable with generics incorrectly
Missing 'new' keyword or wrong constructor
3. Consider the following C# code using a BST and a Dictionary. What will be the output?
var bst = new SortedSet<int>();
bst.Add(10);
bst.Add(5);
bst.Add(15);
var dict = new Dictionary();
dict[10] = "Ten";
dict[5] = "Five";
dict[15] = "Fifteen";
Console.WriteLine(string.Join(",", bst));
Console.WriteLine(string.Join(",", dict.Keys));
medium
A. 5,10,15
10,5,15
B. 5,10,15
5,10,15
C. 10,5,15
5,10,15
D. 10,5,15
10,5,15
Solution
Step 1: Understand SortedSet iteration order
SortedSet stores elements in sorted order, so iterating bst yields 5,10,15.
Step 2: Understand Dictionary key order
Dictionary keys are iterated in insertion order in .NET Core 3.0+, so keys are 10,5,15 inserted in that order.
Step 3: Check output
But the code prints dict.Keys with string.Join, which preserves insertion order: 10,5,15.
Final Answer:
5,10,15
10,5,15 -> Option A
Quick Check:
BST sorted, Dictionary insertion order [OK]
Hint: SortedSet sorts; Dictionary keys keep insertion order [OK]
Common Mistakes:
Assuming Dictionary keys are sorted
Confusing SortedSet with HashSet
Ignoring insertion order of Dictionary keys
4. The following C# code tries to use a Dictionary to get the smallest key quickly. What is the main issue?
var dict = new Dictionary();
dict[20] = "Twenty";
dict[10] = "Ten";
dict[30] = "Thirty";
int minKey = dict.Keys.Min();
Console.WriteLine(minKey);
medium
A. Min() method does not exist for Keys collection
B. Dictionary does not have a Keys property
C. Dictionary.Keys.Min() is inefficient for large data
D. Code will throw a runtime exception
Solution
Step 1: Check Dictionary.Keys property
Dictionary has a Keys property returning a collection of keys.
Step 2: Check Min() method usage
Keys collection supports LINQ Min() to find smallest key, but it requires scanning all keys.
Step 3: Identify issue
Finding min key by scanning all keys is inefficient compared to BST which keeps keys sorted.
Final Answer:
Dictionary.Keys.Min() is inefficient for large data -> Option C
Quick Check:
Min key in Dictionary is slow [OK]
Hint: Dictionary min key needs full scan, slow for big data [OK]
Common Mistakes:
Thinking Dictionary.Keys.Min() is invalid syntax
Assuming Dictionary keeps keys sorted
Expecting constant time min key retrieval
5. You need to store a large dataset of user IDs (integers) with associated names, and you must frequently perform these operations:
Insert new users
Find a user by ID quickly
List users in ascending order of IDs
Delete users
Which data structure or combination is the best choice in C# to optimize all these operations efficiently?
hard
A. Use List> and sort before each listing
B. Use only Dictionary for all operations
C. Use Dictionary for fast lookup and a separate SortedSet<int> for ordering
D. Use only SortedDictionary for all operations
Solution
Step 1: Analyze operation requirements
Need fast insert, delete, lookup, and ordered listing by user ID.
Step 2: Compare data structures
Dictionary offers fast lookup but no order; SortedDictionary keeps keys sorted and supports fast lookup, insert, delete.
Step 3: Evaluate combined approach
Using Dictionary + SortedSet adds complexity and overhead; SortedDictionary handles all efficiently.
Final Answer:
Use only SortedDictionary<int, string> for all operations -> Option D
Quick Check:
SortedDictionary fits all needs best [OK]
Hint: SortedDictionary keeps keys sorted with fast lookup [OK]
Common Mistakes:
Using Dictionary alone and sorting keys each time
Using List and sorting repeatedly, inefficient
Combining Dictionary and SortedSet unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.