Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the map field in the HashMap struct.
DSA Go
type HashMap struct {
buckets map[int][]KeyValue
}
type KeyValue struct {
key string
value string
}
func NewHashMap() *HashMap {
return &HashMap{
buckets: [1],
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a slice instead of a map for buckets.
Not initializing the map with make.
Using map literal without make in constructor.
✗ Incorrect
We use make to initialize the map field properly in Go.
2fill in blank
mediumComplete the code to compute the hash index for a given key.
DSA Go
func (h *HashMap) hash(key string) int {
var hash int
for _, ch := range key {
hash += int(ch)
}
return hash [1] len(h.buckets)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using division instead of modulo.
Using multiplication which increases the number.
Adding length instead of modulo.
✗ Incorrect
We use modulo operator % to keep the hash index within bucket size.
3fill in blank
hardFix the error in the Put method to update the value if key exists or append if not.
DSA Go
func (h *HashMap) Put(key, value string) {
index := h.hash(key)
bucket := h.buckets[index]
for i, kv := range bucket {
if kv.key == key {
bucket[i].value = [1]
h.buckets[index] = bucket
return
}
}
h.buckets[index] = append(bucket, KeyValue{key, value})
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning key instead of value.
Assigning index or bucket which are wrong types.
Not updating the map after change.
✗ Incorrect
We assign the new value to the existing key's value field.
4fill in blank
hardFill both blanks to complete the Get method that returns the value and a boolean if found.
DSA Go
func (h *HashMap) Get(key string) (string, bool) {
index := h.hash(key)
bucket := h.buckets[[1]]
for _, kv := range bucket {
if kv.key == [2] {
return kv.value, true
}
}
return "", false
}Attempts:
3 left
💡 Hint
Common Mistakes
Using h.hash(key) directly as bucket index in code instead of variable.
Comparing with index instead of key.
Accessing h.buckets incorrectly.
✗ Incorrect
We use index to access the bucket and key to compare keys inside the bucket.
5fill in blank
hardFill all three blanks to complete the Remove method that deletes a key from the map.
DSA Go
func (h *HashMap) Remove(key string) {
index := h.hash(key)
bucket := h.buckets[index]
for i, kv := range bucket {
if kv.key == [1] {
bucket = append(bucket[:[2]], bucket[[3]:]...)
h.buckets[index] = bucket
return
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using index instead of i for slicing.
Using i instead of key for comparison.
Incorrect slice indices causing runtime errors.
✗ Incorrect
We compare with key, remove element at index i by slicing before and after i.
