Problem Link: Spell Check
Problem Statement:
You are given a list of words contained in the dictionary and you have to check if a certain word is correct i.e. it is present in this dictionary or not.
Output correct
if it is present in the dictionary, Otherwise print incorrect
.
Approach:
The key idea of this solution is to use a Trie (pronounced as “try”), which is a specialized tree-like data structure used for storing a dynamic set of strings. Each node in the Trie represents a character of a word, and it allows for efficient insertion and search operations.
-
TrieNode Structure:
-
Each
TrieNode
has an array of pointers (children
) to its child nodes, representing the next characters in the words. -
A boolean flag (
isEndOfWord
) indicates if the node marks the end of a valid word.
-
-
Trie Class: insert(const string& word):
-
This function inserts a word into the Trie by iterating through each character of the word.
-
For each character, it checks if the corresponding child node exists; if not, it creates a new node.
-
Once all characters of the word are processed, it marks the last node as the end of a word.
-
-
search(const string& word):
-
This function searches for a word in the Trie by checking if the characters exist in sequence.
-
It returns true if the word exists in the Trie and is marked as an end of a word.
-
-
Main Function:
-
First, it reads a number of words to be inserted into the Trie.
-
It then reads words to be searched and prints “correct” if found and “incorrect” otherwise.
-
Time Complexity:
-
Insertion: O(m) where
m
is the length of the word being inserted. -
Search: O(m) where
m
is the length of the word being searched.
Space Complexity:
- O(n * m) where
n
is the number of words andm
is the average length of the words, as each word can create up to m nodes in the Trie.