A Trie stores words character by character in a tree, making it easy to find all words sharing a prefix by traversing the tree. A Hash Map uses hashing of whole keys, so it cannot efficiently find keys by partial prefixes.
const words = ['apple', 'app', 'application', 'bat']; // Trie prefix search result for 'app' const trieResult = ['app', 'apple', 'application']; // Hash Map keys const hashMap = { apple: 1, app: 1, application: 1, bat: 1 }; // Hash Map prefix search simulation const hashMapResult = Object.keys(hashMap).filter(word => word.startsWith('app'));
The Trie stores words in a way that prefix search returns all words starting with 'app'. The Hash Map keys can be filtered by prefix using startsWith, so both return the same list here.
However, in practice, Hash Map prefix search is inefficient for large data sets.
Autocomplete requires quickly finding all keys starting with a prefix. Hash Maps store keys hashed and unordered, so to find all keys with a prefix, you must check every key, which is slow. Tries organize keys by prefix inherently.
Object.keys returns all keys in the Hash Map. The filter then checks each key with startsWith, so the time grows linearly with the number of keys. This is inefficient for large data sets.
Tries represent keys as paths in a tree, where each node is a character. This structure allows all keys sharing a prefix to share the same path, so prefix operations traverse the prefix path once and then explore children efficiently. Hash Maps do not have this structure.