Open In App

Implement a Dictionary using Trie

Last Updated : 23 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads