
Problem
Solution
Submissions
Hash Table Implementation
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to implement a hash table (using separate chaining for collision resolution) and perform basic operations such as insertion, deletion, and searching for elements.
Example 1
- Input: Operations =
1. Insert: (1, "Apple"), (2, "Banana"), (3, "Cherry"), (12, "Grape")
2. Search for key 3
3. Delete key 2
4. Search for key 2
5. Insert: (22, "Orange")
6. Search for key 22 - Output:
Value for key 3: Cherry
Key 2 deleted
Key 2 not found
Value for key 22: Orange - Explanation:
- Step 1: Implement a hash table with separate chaining.
- Step 2: Insert the key-value pairs (1, "Apple"), (2, "Banana"), (3, "Cherry"), and (12, "Grape").
- Step 3: Search for key 3 and return "Cherry".
- Step 4: Delete key 2 and confirm deletion.
- Step 5: Search for the deleted key 2 and report it as not found.
- Step 6: Insert the key-value pair (22, "Orange").
- Step 7: Search for key 22 and return "Orange".
Example 2
- Input: Operations =
1. Insert: (10, "Ten"), (20, "Twenty"), (30, "Thirty"), (10, "NewTen")
2. Search for key 10
3. Delete key 30
4. Search for key 30
5. Insert: (40, "Forty")
6. Search for key 40 - Output:
Value for key 10: NewTen
Key 30 deleted
Key 30 not found
Value for key 40: Forty - Explanation:
- Step 1: Implement a hash table with separate chaining.
- Step 2: Insert the key-value pairs (10, "Ten"), (20, "Twenty"), (30, "Thirty"), and update (10, "NewTen").
- Step 3: Search for key 10 and return "NewTen" (note: the value was updated).
- Step 4: Delete key 30 and confirm deletion.
- Step 5: Search for the deleted key 30 and report it as not found.
- Step 6: Insert the key-value pair (40, "Forty").
- Step 7: Search for key 40 and return "Forty".
Constraints
- 1 ≤ Number of operations ≤ 10^4
- -10^9 ≤ Key values ≤ 10^9
- 1 ≤ String length ≤ 100
- Time Complexity: O(1) on average for insertion, deletion, and search operations
- Space Complexity: O(n) where n is the number of elements in the hash table
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use an array of linked lists to implement separate chaining.
- Define a hash function to map keys to indices in the array.
- For insertion, compute the hash, find the correct chain, and add the key-value pair.
- For searching, compute the hash, find the correct chain, and search for the key.
- For deletion, compute the hash, find the correct chain, and remove the node with the given key.
- Handle collisions by adding new elements to the front or end of the linked list at the hash index.
- Consider implementing a rehashing mechanism to maintain a good load factor.