Bird
Raised Fist0
DSA Pythonprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of a HashMap in data structures?
easy
A. To store key-value pairs for fast data retrieval
B. To store data in a sorted order
C. To perform mathematical calculations
D. To store data in a sequential list

Solution

  1. Step 1: Understand what a HashMap stores

    A HashMap stores data as key-value pairs, allowing quick access to values using keys.
  2. Step 2: Identify the main purpose

    The main purpose is to retrieve data quickly by keys, not to sort or calculate.
  3. Final Answer:

    To store key-value pairs for fast data retrieval -> Option A
  4. Quick Check:

    HashMap = fast key-value access [OK]
Hint: Remember: HashMap = key-value pairs for quick lookup [OK]
Common Mistakes:
  • Confusing HashMap with sorted data structures
  • Thinking HashMap stores data sequentially
  • Assuming HashMap is for calculations
2. Which of the following is the correct way to define a simple HashMap class constructor in Python?
easy
A. def __init__(self): self.map = set()
B. def __init__(self): self.map = []
C. def __init__(self): self.map = {}
D. def __init__(self): self.map = ()

Solution

  1. Step 1: Identify the data structure for storing key-value pairs

    A HashMap stores key-value pairs, so a dictionary {} is appropriate.
  2. Step 2: Check each option's data type

    def __init__(self): self.map = {} uses {} which is a dictionary. Others use list, set, or tuple which are not suitable for key-value mapping.
  3. Final Answer:

    def __init__(self): self.map = {} -> Option C
  4. Quick Check:

    HashMap uses dictionary = {} [OK]
Hint: Use {} to store key-value pairs in Python [OK]
Common Mistakes:
  • Using list or tuple instead of dictionary
  • Confusing set with dictionary
  • Not initializing the map attribute
3. What will be the output of the following code?
class HashMap:
    def __init__(self):
        self.map = {}
    def put(self, key, value):
        self.map[key] = value
    def get(self, key):
        return self.map.get(key, None)

h = HashMap()
h.put('a', 1)
h.put('b', 2)
print(h.get('a'))
print(h.get('c'))
medium
A. 1\nNone
B. 1\n0
C. None\nNone
D. Error

Solution

  1. Step 1: Trace the put method calls

    Keys 'a' and 'b' are added with values 1 and 2 respectively.
  2. Step 2: Trace the get method calls

    Getting 'a' returns 1. Getting 'c' returns None because 'c' is not in the map and default is None.
  3. Final Answer:

    1\nNone -> Option A
  4. Quick Check:

    Existing key returns value, missing key returns None [OK]
Hint: get() returns None if key not found by default [OK]
Common Mistakes:
  • Expecting 0 instead of None for missing keys
  • Confusing print output format
  • Assuming error on missing key
4. Find the error in this HashMap implementation snippet:
class HashMap:
    def __init__(self):
        self.map = []
    def put(self, key, value):
        self.map[key] = value
medium
A. Missing return statement in put method
B. No error, code is correct
C. Incorrect method name put instead of add
D. Using list instead of dictionary for self.map

Solution

  1. Step 1: Check the data structure used for self.map

    self.map is initialized as a list, but lists do not support key-based assignment.
  2. Step 2: Understand why list causes error

    Using self.map[key] = value will cause TypeError because list indices must be integers, not keys.
  3. Final Answer:

    Using list instead of dictionary for self.map -> Option D
  4. Quick Check:

    List can't use keys as indices [OK]
Hint: Use dictionary {} for key-value storage, not list [] [OK]
Common Mistakes:
  • Thinking put method needs return
  • Confusing method names
  • Ignoring data type of self.map
5. You want to implement a HashMap that handles collisions by chaining (using lists). Which of the following code snippets correctly initializes the internal storage for chaining?
hard
A. self.map = {}
B. self.map = [[] for _ in range(size)]
C. self.map = [None] * size
D. self.map = [0] * size

Solution

  1. Step 1: Understand chaining collision handling

    Chaining uses a list of lists where each bucket holds a list of key-value pairs.
  2. Step 2: Identify correct initialization

    self.map = [[] for _ in range(size)] creates a list of empty lists, one for each bucket, suitable for chaining.
  3. Step 3: Why other options are incorrect

    self.map = [None] * size creates a list of None, which needs extra checks. self.map = {} is a dictionary, not a list of buckets. self.map = [0] * size creates a list of zeros, not suitable for chaining.
  4. Final Answer:

    self.map = [[] for _ in range(size)] -> Option B
  5. Quick Check:

    Chaining needs list of lists = [[] for _ in range(size)] [OK]
Hint: Use list comprehension to create buckets for chaining [OK]
Common Mistakes:
  • Using None or 0 instead of empty lists for buckets
  • Confusing dictionary with list of buckets
  • Not initializing buckets properly for chaining
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard