Implement a Dictionary using Trie
Last Updated :
23 Mar, 2023
Implement a dictionary using Trie such that if the input is a string representing a word, the program prints its meaning from the prebuilt dictionary.
Examples:
Input: str = "map"
Output: a diagrammatic representation of an area
Input: str = "language"
Output: the method of human communication
Approach: We can use a Trie to efficiently store strings and search them. Here, an implementation of a dictionary using Trie (memory optimization using hash-map) is discussed. We add another field to Trie node, a string which will hold the meaning of a word. While searching for the meaning of the required word, we search for the word in Trie and if the word is present (i.e isEndOfWord = true) then we return its meaning otherwise we return an empty string.
Below is the implementation of the above approach:
CPP
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Structure for Trie
struct Trie {
bool isEndOfWord;
unordered_map<char, Trie*> map;
string meaning;
};
// Function to create a new Trie node
Trie* getNewTrieNode()
{
Trie* node = new Trie;
node->isEndOfWord = false;
return node;
}
// Function to insert a word with its meaning
// in the dictionary built using a Trie
void insert(Trie*& root, const string& str,
const string& meaning)
{
// If root is null
if (root == NULL)
root = getNewTrieNode();
Trie* temp = root;
for (int i = 0; i < str.length(); i++) {
char x = str[i];
// Make a new node if there is no path
if (temp->map.find(x) == temp->map.end())
temp->map[x] = getNewTrieNode();
temp = temp->map[x];
}
// Mark end of word and store the meaning
temp->isEndOfWord = true;
temp->meaning = meaning;
}
// Function to search a word in the Trie
// and return its meaning if the word exists
string getMeaning(Trie* root, const string& word)
{
// If root is null i.e. the dictionary is empty
if (root == NULL)
return "";
Trie* temp = root;
// Search a word in the Trie
for (int i = 0; i < word.length(); i++) {
temp = temp->map[word[i]];
if (temp == NULL)
return "";
}
// If it is the end of a valid word stored
// before then return its meaning
if (temp->isEndOfWord)
return temp->meaning;
return "";
}
// Driver code
int main()
{
Trie* root = NULL;
// Build the dictionary
insert(root, "language", "the method of human communication");
insert(root, "computer", "A computer is a machine that can be \
instructed to carry out sequences of arithmetic or \
logical operations automatically via computer programming");
insert(root, "map", "a diagrammatic representation \
of an area");
insert(root, "book", "a written or printed work \
consisting of pages glued or sewn together along one \
side and bound in covers.");
insert(root, "science", "the intellectual and \
practical activity encompassing the systematic study \
of the structure and behaviour of the physical and \
natural world through observation and experiment.");
string str = "map";
cout << getMeaning(root, str);
return 0;
}
Java
// Java implementation of the approach
import java.util.HashMap;
// Structure for Trie
class Trie {
boolean isEndOfWord;
HashMap<Character, Trie> map;
String meaning;
Trie() {
this.isEndOfWord = false;
this.map = new HashMap<>();
this.meaning = "";
}
}
public class Main {
// Function to insert a word with its meaning
// in the dictionary built using a Trie
static void insert(Trie root, String word, String meaning) {
Trie temp = root;
for (int i = 0; i < word.length(); i++) {
char x = word.charAt(i);
// Make a new node if there is no path
if (!temp.map.containsKey(x))
temp.map.put(x, new Trie());
temp = temp.map.get(x);
}
// Mark end of word and store the meaning
temp.isEndOfWord = true;
temp.meaning = meaning;
}
// Function to search a word in the Trie
// and return its meaning if the word exists
static String getMeaning(Trie root, String word) {
Trie temp = root;
// Search a word in the Trie
for (int i = 0; i < word.length(); i++) {
char x = word.charAt(i);
if (!temp.map.containsKey(x))
return "";
temp = temp.map.get(x);
}
// If it is the end of a valid word stored
// before then return its meaning
if (temp.isEndOfWord)
return temp.meaning;
return "";
}
public static void main(String[] args) {
Trie root = new Trie();
// Build the dictionary
insert(root, "language", "the method of human communication");
insert(root, "computer", "A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming");
insert(root, "map", "a diagrammatic representation of an area");
insert(root, "book", "a written or printed work consisting of pages glued or sewn together along one side and bound in covers.");
insert(root, "science", "the intellectual and practical activity encompassing the systematic study of the structure and behaviour of the physical and natural world through observation and experiment.");
String word = "map";
System.out.println(getMeaning(root, word));
}
}
// This code is contributed by Aman Kumar.
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
// Structure for Trie
class TrieNode {
public bool isEndOfWord;
public Dictionary<char, TrieNode> map;
public string meaning;
public TrieNode() {
isEndOfWord = false;
map = new Dictionary<char, TrieNode>();
meaning = "";
}
}
class MainClass {
// Function to insert a word with its meaning
// in the dictionary built using a Trie
static void insert(TrieNode root, string word, string meaning) {
TrieNode temp = root;
for (int i = 0; i < word.Length; i++) {
char x = word[i];
// Make a new node if there is no path
if (!temp.map.ContainsKey(x))
temp.map[x] = new TrieNode();
temp = temp.map[x];
}
// Mark end of word and store the meaning
temp.isEndOfWord = true;
temp.meaning = meaning;
}
// Function to search a word in the Trie
// and return its meaning if the word exists
static string getMeaning(TrieNode root, string word) {
TrieNode temp = root;
// Search a word in the Trie
for (int i = 0; i < word.Length; i++) {
char x = word[i];
if (!temp.map.ContainsKey(x))
return "";
temp = temp.map[x];
}
// If it is the end of a valid word stored
// before then return its meaning
if (temp.isEndOfWord)
return temp.meaning;
return "";
}
static void Main(string[] args) {
TrieNode root = new TrieNode();
// Build the dictionary
insert(root, "language", "the method of human communication");
insert(root, "computer", "A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming");
insert(root, "map", "a diagrammatic representation of an area");
insert(root, "book", "a written or printed work consisting of pages glued or sewn together along one side and bound in covers.");
insert(root, "science", "the intellectual and practical activity encompassing the systematic study of the structure and behaviour of the physical and natural world through observation and experiment.");
string word = "map";
Console.WriteLine(getMeaning(root, word));
}
}
// This code is contributed by Utkarsh Kumar.
Python3
# Python implementation of the above approach
class Trie:
# Trie constructor
def __init__(self):
self.isEndOfWord = False
self.map = {}
self.meaning = ""
# Function to insert a word with its meaning
# in the dictionary built using a Trie
def insert(root, word, meaning):
temp = root
for i in range(len(word)):
x = word[i]
# If there is no path then make a new node
if x not in temp.map:
temp.map[x] = Trie()
temp = temp.map[x]
# Mark end of word and store the meaning
temp.isEndOfWord = True
temp.meaning = meaning
# Function to search a word in the Trie
# and return its meaning if the word exists
def getMeaning(root, word):
temp = root
# Search a word in the Trie
for i in range(len(word)):
x = word[i]
if x not in temp.map:
return ""
temp = temp.map[x]
# If it is the end of a valid word stored
# before then return its meaning
if temp.isEndOfWord:
return temp.meaning
return ""
# Driver code
if __name__ == "__main__":
root = Trie()
# Build the dictionary
insert(root, "language", "the method of human communication")
insert(root, "computer", "A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming")
insert(root, "map", "a diagrammatic representation of an area")
insert(root, "book", "a written or printed work consisting of pages glued or sewn together along one side and bound in covers.")
insert(root, "science", "the intellectual and practical activity encompassing the systematic study of the structure and behaviour of the physical and natural world through observation and experiment.")
word = "map"
print(getMeaning(root, word))
JavaScript
// JavaScript implementation of the approach
class TrieNode {
constructor() {
this.isEndOfWord = false;
this.map = new Map();
this.meaning = "";
}
}
// Function to insert a word with its meaning
// in the dictionary built using a Trie
function insert(root, word, meaning) {
let temp = root;
for (let i = 0; i < word.length; i++) {
const x = word[i];
// Make a new node if there is no path
if (!temp.map.has(x)) {
temp.map.set(x, new TrieNode());
}
temp = temp.map.get(x);
}
// Mark end of word and store the meaning
temp.isEndOfWord = true;
temp.meaning = meaning;
return root;
}
// Function to search a word in the Trie
// and return its meaning if the word exists
function getMeaning(root, word) {
let temp = root;
// Search a word in the Trie
for (let i = 0; i < word.length; i++) {
const x = word[i];
if (!temp.map.has(x)) {
return "";
}
temp = temp.map.get(x);
}
// If it is the end of a valid word stored
// before then return its meaning
if (temp.isEndOfWord) {
return temp.meaning;
}
return "";
}
// Usage
let root = new TrieNode();
root = insert(root, "language", "the method of human communication");
root = insert(root, "computer", "A computer is a machine that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming");
root = insert(root, "map", "a diagrammatic representation of an area");
root = insert(root, "book", "a written or printed work consisting of pages glued or sewn together along one side and bound in covers.");
root = insert(root, "science", "the intellectual and practical activity encompassing the systematic study of the structure and behaviour of the physical and natural world through observation and experiment.");
const word = "map";
document.write(getMeaning(root, word));
Output:a diagrammatic representation of an area
Similar Reads
Auto-complete feature using Trie We are given a Trie with a set of strings stored in it. Now the user types in a prefix of his search query, we need to give him all recommendations to auto-complete his query based on the strings stored in the Trie. We assume that the Trie stores past searches by the users.For example if the Trie st
10 min read
Spell Checker using Trie Given an array of strings str[] and a string key, the task is to check if the spelling of the key is correct or not. If found to be true, then print "YES". Otherwise, print the suggested correct spellings. Examples: Input:str[] = { âgeeâ, âgeeksâ, âapeâ, âappleâ, âgeeksforgeeksâ }, key = âgeekâ Outp
11 min read
Boggle using Trie Given a dictionary, a method to do a lookup in the dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of
15+ min read
Trie memory optimization using hash map We introduced and discussed an implementation in below post. Trie | (Insert and Search) - GeeksforGeeks The implementation used in above post uses an array of alphabet size with every node. It can be made memory efficient. One way to implementing Trie is linked set of nodes, where each node contains
7 min read
Persistent Trie | Set 1 (Introduction) Prerequisite: TriePersistency in Data Structure Trie is one handy data structure that often comes into play when performing multiple string lookups. In this post, we will introduce the concept of Persistency in this data structure. Persistency simply means to retain the changes. But obviously, retai
15+ min read