We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Trie
- Contacts
- Discussions
Contacts
Contacts
Sort by
recency
|
335 Discussions
|
Please Login in order to post a comment
My best C++ solution using Unordered_map. It may not be safe and I think I'm breaking some rules, but it was the closest I could get. It passed all tests.
.
Solution Using a Trie
In this problem, we need to implement a contact management system that efficiently handles two operations:
A naive approach that scans all contacts would be inefficient, particularly with large datasets. Instead, we leverage a Trie (prefix tree) to store and search contacts efficiently, achieving optimal performance.
Approach
We implement a Trie-based solution for fast insertions and prefix lookups:
TrieNode Structure Each node in the Trie holds:
children
: A HashMap storing child nodes.words
: A counter tracking words passing through the node.Trie Operations
add(String s)
: Inserts a word character by character, updating the words count at each step.find(String partial)
: Traverses the Trie to count how many words share the given prefix.Processing Queries The solution efficiently processes
"add"
and"find"
operations using Trie methods.Complexity Analysis
add
) → O(n) wheren
is the length of the word.find
) → O(m) wherem
is the length of the prefix.Java:
C# solution using a tree where each node has potentially 26 children.
}
This is my solution for Python 3.5+ using dictionaries.
Simple java code using Trie -
class TrieNode{ TrieNode[] children = new TrieNode[26]; int we,prefix; public TrieNode(){ we=0; prefix=0; for(int i=0;i<26;i++) children[i]=null; } }
class Result {
} }