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.
Here my solution. The Fast version of the find matches function passes the time limit too. Nice problem.
classTrieElement{public:usingTrieElementPtr=std::unique_ptr<TrieElement>;usingTrieElementRawPtr=TrieElement*;std::unordered_map<char,TrieElementPtr>children_;boolis_word{false};uint32_twords_underneath{0};};classTrie{public:voidAddWord(conststd::string&word_str){if(word_str.empty())return;autocurrent_node=&root_;for(constcharletter:word_str){if(notcurrent_node->children_.count(letter))current_node->children_[letter]=std::make_unique<TrieElement>();current_node=current_node->children_.at(letter).get();++current_node->words_underneath;}current_node->is_word=true;}uint32_tFindPartialMatches(conststd::string&query_str){uint32_tmatches{0};autonode=FindLastNodeForQuery(query_str);if(notnode)returnmatches;// from here we start looking for partialsstd::queue<TrieElement::TrieElementRawPtr>search_queue;search_queue.push(node);while(notsearch_queue.empty()){constautocurrent=search_queue.front();search_queue.pop();if(current->is_word){++matches;}// get children and add them to queuefor(constauto&pair:current->children_){search_queue.push(pair.second.get());}}returnmatches;}boolFindExact(conststd::string&query_str){autonode=FindLastNodeForQuery(query_str);if(notnode)returnfalse;returnnode->is_word;}uint32_tFindPartialMatchesFast(conststd::string&query_str){autonode=FindLastNodeForQuery(query_str);if(notnode)return0;returnnode->words_underneath;}private:TrieElement::TrieElementRawPtrFindLastNodeForQuery(conststd::string&query_str){if(query_str.empty())returnnullptr;autocurrent_node=&root_;for(constcharletter:query_str){if(notcurrent_node->children_.count(letter))returnnullptr;current_node=current_node->children_.at(letter).get();}returncurrent_node;}TrieElementroot_;};
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 →
Here my solution. The Fast version of the find matches function passes the time limit too. Nice problem.