Hone logo
Hone
Problems

Implement Deletion from a Go Map

Maps are a fundamental data structure for storing key-value pairs. In Go, the map type provides efficient lookups, insertions, and deletions. This challenge focuses on implementing the deletion of a key-value pair from a Go map. Understanding how to correctly remove elements is crucial for managing dynamic data and optimizing memory usage.

Problem Description

Your task is to write a Go function that safely deletes a specified key from a map. The function should handle cases where the key might not exist in the map.

What needs to be achieved: Create a function that takes a map and a key as input and removes the corresponding key-value pair from the map.

Key requirements:

  • The function should accept a map and a key as arguments.
  • The function should modify the map in place.
  • The function should not panic if the key to be deleted does not exist in the map.

Expected behavior:

  • If the key exists, the corresponding entry should be removed from the map.
  • If the key does not exist, the map should remain unchanged.

Edge cases to consider:

  • Deleting from an empty map.
  • Deleting a key that has never been present.
  • Deleting the only key in a map.

Examples

Example 1:

Input Map: map[string]int{"apple": 1, "banana": 2, "cherry": 3}
Key to Delete: "banana"

Output Map: map[string]int{"apple": 1, "cherry": 3}

Explanation: The key "banana" exists in the map, so its corresponding entry (key-value pair) is removed.

Example 2:

Input Map: map[string]int{"apple": 1, "banana": 2, "cherry": 3}
Key to Delete: "grape"

Output Map: map[string]int{"apple": 1, "banana": 2, "cherry": 3}

Explanation: The key "grape" does not exist in the map, so the map remains unchanged.

Example 3:

Input Map: map[string]int{"single": 100}
Key to Delete: "single"

Output Map: map[string]int{}

Explanation: The key "single" exists and is the only element, so its removal results in an empty map.

Example 4:

Input Map: map[string]int{}
Key to Delete: "anything"

Output Map: map[string]int{}

Explanation: The input map is empty, so attempting to delete any key results in an unchanged empty map.

Constraints

  • The map can contain any valid Go key and value types for which equality is defined (e.g., string, int, struct with comparable fields).
  • The key to be deleted will be of the same type as the map's keys.
  • Performance is not a primary concern for this challenge, but the solution should be reasonably efficient.

Notes

Go provides a built-in delete function for maps. Consider how this function behaves and how you can leverage it to meet the requirements. You do not need to implement the map deletion logic from scratch; rather, use Go's existing mechanisms.

Loading editor...
go