Solution Review: Suffix Score
See the solution to the problem challenge.
We'll cover the following...
Solution
#include <iostream>#include <vector>using namespace std;// Definition of a trie nodeclass TrieNode{public:// pointer to the next 26 alphabetsTrieNode *children[26] = {};// in integer to store the number of times// suffix is visitedint cnt = 0;};class Trie{public:TrieNode * root;Trie(){root = new TrieNode();}// inserts the word in reverse order in trievoid insert(string word){// point current node to the rootTrieNode *curr = root;// traverse the word in reverse orderfor (int i = word.size() - 1; i >= 0; i--){int index = word[i] - 'a';//create a new node if not already existingif (!curr->children[index]){curr->children[index] = new TrieNode();}// increment the count// associated with the suffixcurr->children[index]->cnt++;curr = curr->children[index];}}int findSuffixScoreSum(string word){// point current node to the rootTrieNode *curr = root;int scoreSum = 0;// traverse the word in reverse orderfor (int i = word.size() - 1; i >= 0; i--){int index = word[i] - 'a';// add the count associated with each suffixscoreSum += curr->children[index]->cnt;curr = curr->children[index];}return scoreSum;}};vector<int> suffixScores(vector<string> words){int n = words.size();Trie *trie = new Trie();// Insert words in triefor (int i = 0; i < n; i++){trie->insert(words[i]);}vector<int> answer(n, 0);for (int i = 0; i < n; i++){// Get the score of all suffixes of given stringanswer[i] = trie->findSuffixScoreSum(words[i]);}return answer;}
Intuition
The problem can be divided into two parts: first, find all the suffixes of a word; second, for every suffix, find the number of times it appears in the input words and add these count values for all the suffixes of the word. This will be the score
of the word.
Finding all the suffixes of a word is an
We can maintain a cnt
parameter with every trie node. The value of the cnt
on the last node of the suffix string denotes the number of times the given suffix was inserted in the trie. This is similar to the concept used in the suffix count problem.
Since in this case we're dealing with suffixes instead of prefixes, we create a trie of the reverse words.
Algorithm
The summary of the algorithm is given below.
Step 1: Insertion in a trie
Insert all the ...