0
0
DSA Javascriptprogramming~30 mins

Trie vs Hash Map for Prefix Matching in DSA Javascript - Build Both Approaches

Choose your learning style9 modes available
Trie vs Hash Map for Prefix Matching
📖 Scenario: You are building a simple search feature for a phone contacts app. Users want to find contacts quickly by typing the first few letters of a name.Two common ways to do this are using a Trie (a tree-like structure) or a Hash Map (a dictionary). This project will help you understand how both work for prefix matching.
🎯 Goal: Build two data structures: a Trie and a Hash Map that store contact names. Then, find all contacts starting with a given prefix using both methods.
📋 What You'll Learn
Create a list of contact names
Create a prefix string to search
Build a Trie data structure and insert all contacts
Build a Hash Map grouping contacts by their prefixes
Write functions to find contacts starting with the prefix using both Trie and Hash Map
Print the results of both searches
💡 Why This Matters
🌍 Real World
Search features in phone contacts, autocomplete in search bars, and prefix-based filtering in apps.
💼 Career
Understanding Trie and Hash Map helps in building efficient search and autocomplete features, common in software engineering roles.
Progress0 / 4 steps
1
Create the contacts list
Create a list called contacts with these exact names: 'Alice', 'Alfred', 'Bob', 'Bobby', 'Charlie'
DSA Javascript
Hint

Use square brackets [] to create a list (array) and include the names as strings.

2
Set the prefix to search
Create a variable called prefix and set it to the string 'Al'
DSA Javascript
Hint

Use const prefix = 'Al'; to create the prefix variable.

3
Build Trie and Hash Map for prefix matching
Write a class called TrieNode with a constructor that initializes children as an empty object and isEndOfWord as false. Then write a class called Trie with methods insert(word) to add words and startsWith(prefix) to return all words starting with prefix. Also, create a hashMap object that groups contacts by their first two letters as keys. Insert all contacts into both the Trie and the hashMap.
DSA Javascript
Hint

Define TrieNode and Trie classes with the described methods. Use a loop to insert contacts into both data structures.

4
Search and print contacts starting with prefix
Use console.log to print the result of trie.startsWith(prefix) and the result of looking up hashMap[prefix] or an empty list if undefined.
DSA Javascript
Hint

Use console.log(trie.startsWith(prefix)) and console.log(hashMap[prefix] || []) to print the matching contacts.