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”, “Beginner”, “ape”, “apple”, “w3wiki” }, key = “geek”
Output: Beginner w3wiki
Explanation:
The string “geek” not present in the array of strings.
Therefore, the suggested words are { “Beginner”, “w3wiki” }.Input: str[] = { “gee”, “Beginner”, “ape”, “apple”, “arp” }, key = “Beginner”
Output: YES.
Approach:The problem can be solved using Trie. The idea is to traverse the array of string, str[] and insert the string into the Trie such that each node of the Trie contains the character of the string and a boolean value to check if the character is the last character of the string or not. Follow the steps below to solve the problem:
- Initialize a Trie, say root, such that each node of the Trie consists of a character of a string and a boolean value to check if the character is the last character of the string or not.
- Traverse the array of strings arr[], and insert all the strings into the Trie.
- Finally, traverse the string key. For every ith character, check if the character is present in the Trie or not. If found to be true, then move to the next node of the Trie.
- Otherwise, print all possible strings whose prefix is the string key.
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Structure of a Trie node struct TrieNode { // Store address of a character TrieNode* Trie[256]; // Check if the character is // last character of a string or not bool isEnd; // Constructor function TrieNode() { for ( int i = 0; i < 256; i++) { Trie[i] = NULL; } isEnd = false ; } }; // Function to insert a string into Trie void InsertTrie(TrieNode* root, string s) { TrieNode* temp = root; // Traverse the string, s for ( int i = 0; i < s.length(); i++) { if (temp->Trie[s[i]] == NULL) { // Initialize a node temp->Trie[s[i]] = new TrieNode(); } // Update temp temp = temp->Trie[s[i]]; } // Mark the last character of // the string to true temp->isEnd = true ; } // Function to print suggestions of the string void printSuggestions(TrieNode* root, string res) { // If current character is // the last character of a string if (root->isEnd == true ) { cout << res << " " ; } // Iterate over all possible // characters of the string for ( int i = 0; i < 256; i++) { // If current character // present in the Trie if (root->Trie[i] != NULL) { // Insert current character // into Trie res.push_back(i); printSuggestions(root->Trie[i], res); res.pop_back(); } } } // Function to check if the string // is present in Trie or not bool checkPresent(TrieNode* root, string key) { // Traverse the string for ( int i = 0; i < key.length(); i++) { // If current character not // present in the Trie if (root->Trie[key[i]] == NULL) { printSuggestions(root, key.substr(0, i)); return false ; } // Update root root = root->Trie[key[i]]; } if (root->isEnd == true ) { return true ; } printSuggestions(root, key); return false ; } // Driver Code int main() { // Given array of strings vector<string> str = { "gee" , "Beginner" , "ape" , "apple" , "w3wiki" }; string key = "geek" ; // Initialize a Trie TrieNode* root = new TrieNode(); // Insert strings to trie for ( int i = 0; i < str.size(); i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { cout << "YES" ; } return 0; } |
Java
// Java program to implement // the above approach import java.io.*; // Structure of a Trie node class TrieNode { // Store address of a character TrieNode Trie[]; // Check if the character is // last character of a string or not boolean isEnd; // Constructor function public TrieNode() { Trie = new TrieNode[ 256 ]; for ( int i = 0 ; i < 256 ; i++) { Trie[i] = null ; } isEnd = false ; } } class GFG{ // Function to insert a string into Trie static void InsertTrie(TrieNode root, String s) { TrieNode temp = root; // Traverse the string, s for ( int i = 0 ; i < s.length(); i++) { if (temp.Trie[s.charAt(i)] == null ) { // Initialize a node temp.Trie[s.charAt(i)] = new TrieNode(); } // Update temp temp = temp.Trie[s.charAt(i)]; } // Mark the last character of // the string to true temp.isEnd = true ; } // Function to print suggestions of the string static void printSuggestions(TrieNode root, String res) { // If current character is // the last character of a string if (root.isEnd == true ) { System.out.print(res + " " ); } // Iterate over all possible // characters of the string for ( int i = 0 ; i < 256 ; i++) { // If current character // present in the Trie if (root.Trie[i] != null ) { // Insert current character // into Trie res += ( char )i; printSuggestions(root.Trie[i], res); res = res.substring( 0 , res.length() - 2 ); } } } // Function to check if the string // is present in Trie or not static boolean checkPresent(TrieNode root, String key) { // Traverse the string for ( int i = 0 ; i < key.length(); i++) { // If current character not // present in the Trie if (root.Trie[key.charAt(i)] == null ) { printSuggestions(root, key.substring( 0 , i)); return false ; } // Update root root = root.Trie[key.charAt(i)]; } if (root.isEnd == true ) { return true ; } printSuggestions(root, key); return false ; } // Driver Code public static void main(String[] args) { // Given array of strings String str[] = { "gee" , "Beginner" , "ape" , "apple" , "w3wiki" }; String key = "geek" ; // Initialize a Trie TrieNode root = new TrieNode(); // Insert strings to trie for ( int i = 0 ; i < str.length; i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { System.out.println( "YES" ); } } } // This code is contributed by Dharanendra L V. |
Python3
# Python program to implement # the above approach # Structure of a Trie node class TrieNode: def __init__( self ): # Store address of a character self .trie = [ None ] * 256 # Check if the character is # last character of a string or not self .isEnd = False # Function to insert a string into Trie def insert_trie(root, s): temp = root # Traverse the string, s for i in range ( len (s)): if not temp.trie[ ord (s[i])]: # Initialize a node temp.trie[ ord (s[i])] = TrieNode() # Update temp temp = temp.trie[ ord (s[i])] # Mark the last character of # the string to true temp.isEnd = True # Function to print suggestions of the string def print_suggestions(root, res): # If current character is # the last character of a string if root.isEnd: print (res,end = " " ) # Iterate over all possible # characters of the string for i in range ( 256 ): # If current character # present in the Trie if root.trie[i]: # Insert current character # into Trie res_list = list (res) res_list.append( chr (i)) print_suggestions(root.trie[i], "".join(res_list)) # Function to check if the string # is present in Trie or not def check_present(root, key): # Traverse the string for i in range ( len (key)): # If current character not # present in the Trie if not root.trie[ ord (key[i])]: print_suggestions(root, key[:i]) return False # Update root root = root.trie[ ord (key[i])] if root.isEnd: return True print_suggestions(root, key) return False # Driver Code # Given array of strings strs = [ "gee" , "Beginner" , "ape" , "apple" , "w3wiki" ] key = "geek" # Initialize a Trie root = TrieNode() # Insert strings to trie for s in strs: insert_trie(root, s) if check_present(root, key): print ( "YES" ) # This code is contributed by Aman Kumar |
C#
// C# program to implement // the above approach using System; // Structure of a Trie node public class TrieNode { // Store address of a character public TrieNode[] Trie; // Check if the character is // last character of a string or not public bool isEnd; // Constructor function public TrieNode() { Trie = new TrieNode[256]; for ( int i = 0; i < 256; i++) { Trie[i] = null ; } isEnd = false ; } } public class GFG { // Function to insert a string into Trie static void InsertTrie(TrieNode root, string s) { TrieNode temp = root; // Traverse the string, s for ( int i = 0; i < s.Length; i++) { if (temp.Trie[s[i]] == null ) { // Initialize a node temp.Trie[s[i]] = new TrieNode(); } // Update temp temp = temp.Trie[s[i]]; } // Mark the last character of // the string to true temp.isEnd = true ; } // Function to print suggestions of the string static void printSuggestions(TrieNode root, string res) { // If current character is // the last character of a string if (root.isEnd == true ) { Console.Write(res + " " ); } // Iterate over all possible // characters of the string for ( int i = 0; i < 256; i++) { // If current character // present in the Trie if (root.Trie[i] != null ) { // Insert current character // into Trie res += ( char )i; printSuggestions(root.Trie[i], res); res = res.Substring(0, res.Length - 1); } } } // Function to check if the string // is present in Trie or not static bool checkPresent(TrieNode root, string key) { // Traverse the string for ( int i = 0; i < key.Length; i++) { // If current character not // present in the Trie if (root.Trie[key[i]] == null ) { printSuggestions(root, key.Substring(0, i)); return false ; } // Update root root = root.Trie[key[i]]; } if (root.isEnd == true ) { return true ; } printSuggestions(root, key); return false ; } // Driver Code public static void Main( string [] args) { // Given array of strings string [] str = { "gee" , "Beginner" , "ape" , "apple" , "w3wiki" }; string key = "geek" ; // Initialize a Trie TrieNode root = new TrieNode(); // Insert strings to trie for ( int i = 0; i < str.Length; i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { Console.WriteLine( "YES" ); } } } // This code is contributed by Utkarsh Kumar. |
Javascript
// javascript program to implement // the above approach // Structure of a Trie node class TrieNode { constructor(){ // Store address of a character this .Trie = new Array(256).fill( null ); // Check if the character is // last character of a string or not this .isEnd = false ; } }; // Function to insert a string into Trie function InsertTrie(root, s) { let temp = root; // Traverse the string, s for (let i = 0; i < s.length; i++) { if (temp.Trie[s[i].charCodeAt(0)] == null ) { // Initialize a node temp.Trie[s[i].charCodeAt(0)] = new TrieNode(); } // Update temp temp = temp.Trie[s[i].charCodeAt(0)]; } // Mark the last character of // the string to true temp.isEnd = true ; } // Function to print suggestions of the string function printSuggestions(root, res) { // If current character is // the last character of a string if (root.isEnd == true ) { document.write(res + " " ); } // Iterate over all possible // characters of the string for (let i = 0; i < 256; i++) { // If current character // present in the Trie if (root.Trie[i] != null ) { // Insert current character // into Trie let res_list = res.split( '' ); res_list.push(String.fromCharCode(i)) printSuggestions(root.Trie[i], res_list.join( "" )); } } } // Function to check if the string // is present in Trie or not function checkPresent(root, key) { // Traverse the string for (let i = 0; i < key.length; i++) { // If current character not // present in the Trie if (root.Trie[key[i].charCodeAt(0)] == null ) { printSuggestions(root, key.substr(0, i)); return false ; } // Update root root = root.Trie[key[i].charCodeAt(0)]; } if (root.isEnd == true ) { return true ; } printSuggestions(root, key); return false ; } // Driver Code // Given array of strings let str = [ "gee" , "Beginner" , "ape" , "apple" , "w3wiki" ]; let key = "geek" ; // Initialize a Trie let root = new TrieNode(); // Insert strings to trie for (let i = 0; i < str.length; i++) { InsertTrie(root, str[i]); } if (checkPresent(root, key)) { console.log( "YES" ); } // The code is contributed by Nidhi goel. |
Beginner w3wiki
Time Complexity: O(N * M), where M is the maximum length of the string
Auxiliary Space: O(N * 256)