Implemented using Trie or HashMap
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-02-26
Problem Statement
Design a system that supports efficient insertion, search, and retrieval of key-value pairs, where keys are strings. The system should allow fast exact and prefix-based searches, and can be implemented using either a Trie or a HashMap.
Functional Requirements (FR)
Basic Operations
•insert(key, value) – add a new key-value pair.
•get(key) – retrieve the value for a given key.
•delete(key) – remove a key-value pair.
Prefix Search (Trie Specific)
•searchByPrefix(prefix) – retrieve all key-value pairs that match the given prefix.
Iteration
•Iterate over all keys or key-value pairs.
Concurrency (Optional)
•Support concurrent reads/writes safely.
Suggested Classes & Responsibilities
Class: KeyValueStore
•Attributes:
•storage → either Trie or HashMap depending on chosen implementation
•Methods:
•insert(key, value)
•get(key)
•delete(key)
•searchByPrefix(prefix) (if Trie)
Class: TrieNode (if using Trie)
•Attributes:
•children → map of character → TrieNode
•isEndOfWord → boolean
•value → stores value for complete key
•Methods: standard Trie operations: insert, search, delete, searchByPrefix.
Class: HashMapNode (if using HashMap, internal use optional)
•Attributes: key, value
Data Flow (High-Level)
1.Client calls insert(key, value) → system stores key in Trie or HashMap.
2.Client calls get(key) → system retrieves value.
3.Client calls delete(key) → key removed from storage.
4.Client calls searchByPrefix(prefix) (Trie only) → system returns all matching keys/values.
Key Design Considerations
Time Complexity:
•Trie: O(L) for insert/search/delete, where L is key length.
•HashMap: O(1) average for insert/search/delete.
Memory Efficiency:
•Trie uses more memory due to nodes for each character.
•HashMap uses memory proportional to number of keys.
•Thread-Safety: Use locks or concurrent data structures if accessed concurrently.
•Extensibility: Support advanced operations like auto-complete, prefix matching, or bulk deletion.
•Error Handling: Handle invalid keys, null values, and duplicate keys gracefully.