Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the hash map with empty buckets.
DSA Python
class HashMap: def __init__(self, size=10): self.size = size self.buckets = [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list of zeros instead of empty lists.
Using a dictionary instead of a list of buckets.
✗ Incorrect
We create a list of empty lists, one for each bucket, to store key-value pairs.
2fill in blank
mediumComplete the code to compute the bucket index using the built-in hash function.
DSA Python
def _get_bucket_index(self, key): return [1] % self.size
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the key directly without hashing.
Using length of key which is not unique.
✗ Incorrect
We use the built-in hash function to get a hash value for the key, then mod by size to find the bucket.
3fill in blank
hardFix the error in the put method to update the value if the key already exists.
DSA Python
def put(self, key, value): index = self._get_bucket_index(key) bucket = self.buckets[index] for i, (k, v) in enumerate(bucket): if k == key: bucket[i] = (key, [1]) return bucket.append((key, value))
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the old value instead of the new one.
Using the key or index instead of value.
✗ Incorrect
We replace the old value with the new value for the existing key.
4fill in blank
hardFill both blanks to complete the get method that returns the value or None if key not found.
DSA Python
def get(self, key): index = self._get_bucket_index(key) bucket = self.buckets[index] for k, v in bucket: if k [1] key: return [2] return None
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '=='.
Returning the key instead of the value.
✗ Incorrect
We check if the key matches and return the corresponding value.
5fill in blank
hardFill both blanks to complete the remove method that deletes a key-value pair if it exists.
DSA Python
def remove(self, key): index = self._get_bucket_index(key) bucket = self.bucketsindex] for i, (k, v) in enumerate(bucket): if k [1] key: [2] bucket[i return True return False
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '=='.
Using remove() method instead of del with index.
Forgetting to use brackets for indexing.
✗ Incorrect
We check if keys match, then delete the item at index i from the bucket list.