Implement a Dictionary

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-05-17

Problem Statement

Design and implement a Dictionary (key-value store) that supports insertion, lookup, update, and deletion of entries efficiently. The system should also support optional features like prefix search, auto-complete, and thread-safe operations.


Functional Requirements (FR)


Basic Operations

•insert(key, value) – add a new key-value pair.
•get(key) – retrieve the value associated with a key.
•update(key, newValue) – update the value of an existing key.
•delete(key) – remove a key-value pair.


Search & Retrieval

•Support exact key search.
•Optionally, support prefix-based search for auto-complete or suggestions.


Iteration

•Iterate over keys, values, or key-value pairs.


Concurrency (Optional)

•Ensure thread-safety for multi-threaded access.


Persistence (Optional)

•Support saving and loading the dictionary from disk.


Suggested Classes & Responsibilities


Class: Dictionary


•Attributes:
•storage → underlying data structure (e.g., HashMap, Trie, or TreeMap)
•Methods:
•insert(key, value)
•get(key)
•update(key, value)
•delete(key)
•searchByPrefix(prefix) (optional)
•keys() → return all keys
•values() → return all values


Class (Optional): TrieNode


•Attributes:
•children → map of character to TrieNode
•isEndOfWord → boolean
•value → stores value if this node represents a complete key
•Methods: standard Trie operations for insertion, search, and prefix lookup.


Data Flow (High-Level)


1.Client calls insert(key, value) → Dictionary updates the storage.
2.Client calls get(key) → Dictionary looks up the key in storage and returns value.
3.Client calls update(key, newValue) → Dictionary modifies the value for the key.
4.Client calls delete(key) → key is removed from storage.
5.Optional: Client calls searchByPrefix(prefix) → storage (Trie or alternative) returns matching keys/values.


Key Design Considerations


•Time Complexity: Use HashMap for O(1) lookups or Trie for prefix search.
•Memory Efficiency: Balance memory usage vs search performance.
•Thread-Safety: Use locks or concurrent data structures if accessed concurrently.
•Extensibility: Easily support additional features like persistence, sorting, or versioning.
•Error Handling: Handle invalid keys or null values gracefully.


Solution

Comments