We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
this is the direct question for Trie dataStructure ( best in terms of time and space complexity , correct me if m wrong )
#include<bits/stdc++.h>usingnamespacestd;structNode{intct;// stores the count of words starting from this nodeNode*nextChar[26];// pointers to next charNode(){ct=0;for(inti=0;i<26;i++)nextChar[i]=NULL;}};voidaddString(Node*head,strings){for(autoi:s){// if node doesnot exists then create itif(!head->nextChar[i-'a'])head->nextChar[i-'a']=newNode();head=head->nextChar[i-'a'];// now increment the count for new node// as our word ends at this next characterhead->ct++;}}intfindStringCount(Node*head,strings){for(autoi:s){// if node doesnot exists then return zeroif(!head->nextChar[i-'a'])return0;head=head->nextChar[i-'a'];}returnhead->ct;}intmain(){intn;cin>>n;stringt,s;Noderoot;Node*head=&root;while(n--){cin>>t>>s;head=&root;if(t=="add")addString(head,s);elseif(t=="find")cout<<findStringCount(head,s)<<'\n';}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Contacts
You are viewing a single comment's thread. Return to all comments →
this is the direct question for Trie dataStructure ( best in terms of time and space complexity , correct me if m wrong )