Solution Review: Suffix Score

See the solution to the problem challenge.

Solution

#include <iostream>
#include <vector>
using namespace std;
// Definition of a trie node
class TrieNode
{
public:
// pointer to the next 26 alphabets
TrieNode *children[26] = {};
// in integer to store the number of times
// suffix is visited
int cnt = 0;
};
class Trie
{
public:
TrieNode * root;
Trie()
{
root = new TrieNode();
}
// inserts the word in reverse order in trie
void insert(string word)
{
// point current node to the root
TrieNode *curr = root;
// traverse the word in reverse order
for (int i = word.size() - 1; i >= 0; i--)
{
int index = word[i] - 'a';
//create a new node if not already existing
if (!curr->children[index])
{
curr->children[index] = new TrieNode();
}
// increment the count
// associated with the suffix
curr->children[index]->cnt++;
curr = curr->children[index];
}
}
int findSuffixScoreSum(string word)
{
// point current node to the root
TrieNode *curr = root;
int scoreSum = 0;
// traverse the word in reverse order
for (int i = word.size() - 1; i >= 0; i--)
{
int index = word[i] - 'a';
// add the count associated with each suffix
scoreSum += 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 trie
for (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 string
answer[i] = trie->findSuffixScoreSum(words[i]);
}
return answer;
}
Solution for problem challenge of suffix score in C++

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 O(W)O(W) operation, where WW is the size of the word. Now, to find the number of times the suffix appears in the input words, we can use tries to efficiently solve this problem.

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 ...

Access this course and 1400+ top-rated courses and projects.