0
0
DSA Pythonprogramming~20 mins

HashMap Implementation from Scratch in DSA Python - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
HashMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Basic HashMap Put and Get Operations
What is the output of the following code that uses a simple HashMap implementation to store and retrieve values?
DSA Python
class SimpleHashMap:
    def __init__(self):
        self.size = 5
        self.map = [[] for _ in range(self.size)]

    def _get_hash(self, key):
        return hash(key) % self.size

    def put(self, key, value):
        key_hash = self._get_hash(key)
        key_exists = False
        bucket = self.map[key_hash]
        for i, kv in enumerate(bucket):
            k, v = kv
            if k == key:
                bucket[i] = (key, value)
                key_exists = True
                break
        if not key_exists:
            bucket.append((key, value))

    def get(self, key):
        key_hash = self._get_hash(key)
        bucket = self.map[key_hash]
        for k, v in bucket:
            if k == key:
                return v
        return None

hm = SimpleHashMap()
hm.put('apple', 10)
hm.put('banana', 20)
hm.put('apple', 30)
print(hm.get('apple'))
print(hm.get('banana'))
print(hm.get('cherry'))
A30\n20\n0
B30\n20\nNone
C10\n20\nNone
DNone\nNone\nNone
Attempts:
2 left
💡 Hint
Think about what happens when you put a value for an existing key.
🧠 Conceptual
intermediate
1:30remaining
Understanding HashMap Collision Handling
In a HashMap implemented with separate chaining (using lists for buckets), what happens when two different keys produce the same hash index?
ABoth key-value pairs are stored in the same bucket list at that index.
BThe second key-value pair overwrites the first one at that index.
CThe HashMap throws an error due to collision.
DThe HashMap automatically resizes to avoid collision.
Attempts:
2 left
💡 Hint
Think about how separate chaining works to handle collisions.
🔧 Debug
advanced
2:00remaining
Identify the Bug in HashMap Remove Method
Consider this remove method in a HashMap implementation. What error will occur when trying to remove a key not present in the map?
DSA Python
def remove(self, key):
    key_hash = self._get_hash(key)
    bucket = self.map[key_hash]
    for i, kv in enumerate(bucket):
        k, v = kv
        if k == key:
            del bucket[i]
            return True
    return False

hm = SimpleHashMap()
hm.put('a', 1)
hm.remove('b')
ATypeError because bucket is None.
BIndexError because del bucket[i] tries to delete invalid index.
CNo error; returns False because key not found.
DKeyError because key 'b' is not in the map.
Attempts:
2 left
💡 Hint
What does the method return if the key is not found?
Predict Output
advanced
2:30remaining
Output of HashMap After Multiple Put and Remove Operations
What is the printed output of the HashMap's internal map after these operations?
DSA Python
class SimpleHashMap:
    def __init__(self):
        self.size = 3
        self.map = [[] for _ in range(self.size)]

    def _get_hash(self, key):
        return hash(key) % self.size

    def put(self, key, value):
        key_hash = self._get_hash(key)
        bucket = self.map[key_hash]
        for i, (k, v) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))

    def remove(self, key):
        key_hash = self._get_hash(key)
        bucket = self.map[key_hash]
        for i, (k, v) in enumerate(bucket):
            if k == key:
                del bucket[i]
                return True
        return False

    def __str__(self):
        result = []
        for i, bucket in enumerate(self.map):
            items = ' -> '.join(f'{k}:{v}' for k, v in bucket)
            result.append(f'{i}: {items if items else "null"}')
        return '\n'.join(result)

hm = SimpleHashMap()
hm.put('a', 1)
hm.put('b', 2)
hm.put('c', 3)
hm.put('d', 4)
hm.remove('b')
hm.put('a', 5)
print(hm)
A0: d:4\n1: a:5\n2: c:3
B0: a:5\n1: d:4\n2: c:3
C0: d:4\n1: c:3\n2: a:5
D0: c:3\n1: a:5\n2: d:4
Attempts:
2 left
💡 Hint
Check the hash index for each key and the effect of remove and update.
🧠 Conceptual
expert
2:00remaining
Why Resize a HashMap and How It Affects Performance
Why do we resize a HashMap when the load factor exceeds a threshold, and what is the main effect on performance?
ATo compress keys; reduces key size but increases collision probability.
BTo save memory by decreasing bucket count; reduces memory usage but slows lookup.
CTo sort keys in buckets; improves iteration order but not lookup time.
DTo reduce collisions by increasing bucket count; improves average lookup time from O(n) to O(1).
Attempts:
2 left
💡 Hint
Think about how bucket count affects collisions and lookup speed.