Hone logo
Hone
Problems

Implementing a Simple Key-Value Store in Go

This challenge focuses on implementing the fundamental operations of a key-value store using Go's built-in map data structure. Understanding how to use maps effectively is crucial for many Go programs, enabling efficient data storage and retrieval. You'll be building a simplified version of a dictionary or associative array.

Problem Description

You are tasked with creating a KeyValueStore struct that encapsulates a Go map and provides methods for inserting, retrieving, and deleting key-value pairs. The keys will be strings, and the values will also be strings. Your implementation should handle cases where a key doesn't exist and gracefully manage deletion of non-existent keys.

Key Requirements:

  • Insert(key string, value string): Adds a new key-value pair to the store. If the key already exists, update its value.
  • Get(key string) (string, bool): Retrieves the value associated with a given key. It should return the value and a boolean indicating whether the key exists in the store. If the key doesn't exist, return an empty string and false.
  • Delete(key string): Removes a key-value pair from the store. If the key doesn't exist, the function should do nothing.
  • Size() int: Returns the number of key-value pairs currently stored.

Examples

Example 1:

Input:
  - Insert("apple", "red")
  - Insert("banana", "yellow")
  - Get("apple")
Output: ("red", true)
Explanation: The "apple" key exists and its value is "red".

Example 2:

Input:
  - Insert("apple", "red")
  - Get("orange")
Output: ("", false)
Explanation: The "orange" key does not exist.

Example 3:

Input:
  - Insert("apple", "red")
  - Insert("banana", "yellow")
  - Delete("apple")
  - Get("apple")
Output: ("", false)
Explanation: The "apple" key has been deleted, so it no longer exists.

Example 4:

Input:
  - Insert("apple", "red")
  - Insert("banana", "yellow")
  - Size()
Output: 2
Explanation: There are two key-value pairs in the store.

Constraints

  • Keys and values are strings.
  • The number of insertions, deletions, and retrievals will be within reasonable bounds (less than 1000 operations).
  • The length of keys and values will be less than 256 characters.
  • The solution should be efficient in terms of memory usage.

Notes

  • Go's map type is inherently unordered. You don't need to worry about maintaining any specific order of key-value pairs.
  • Consider using Go's built-in map type directly within your KeyValueStore struct.
  • The Get function's return value of a boolean is important for indicating whether a key exists. This is a common pattern in Go.
  • Think about how to handle the case where a key already exists during insertion. Should you overwrite the existing value? The problem description specifies that you should.
  • Focus on clarity and readability in your code. Good variable names and comments are encouraged.
Loading editor...
go