31. Insert and Search in a Trie
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
For both insert
and search
functions, I'm using recursion to traverse the trie based on the characters of the input key.
In the insert
function, if a character node is not present in the current TrieNode, I create a new node for that character and continue the insertion.
In the search
function, I check for the existence of each character in the trie, and if the end of the key is reached and the current node is a leaf, I return true, indicating a successful search.
Time Complexity : O(N)
, where N is the length of the key. In both insert
and search
functions, we visit each character of the key once.
Auxiliary Space Complexity : O(N)
, where N is the length of the key. The space complexity is determined by the recursion stack depth.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.