From f19cc7af82eb9cd0766e5905c942004fa17f3c70 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Wed, 25 Sep 2024 23:42:56 +0530 Subject: [PATCH] Create 2416. Sum of Prefix Scores of Strings --- 2416. Sum of Prefix Scores of Strings | 56 +++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 2416. Sum of Prefix Scores of Strings diff --git a/2416. Sum of Prefix Scores of Strings b/2416. Sum of Prefix Scores of Strings new file mode 100644 index 0000000..d04ed8f --- /dev/null +++ b/2416. Sum of Prefix Scores of Strings @@ -0,0 +1,56 @@ +// Trie Node definition +class trie { + public: + int x; // To store how many times the prefix ending at this node has been seen. + trie *v[26]; // Array of pointers to children nodes for each character 'a' to 'z'. +}; + +// Function to insert a string into the Trie and update prefix counts +void maketrie(string str, trie* node) { + for (auto &i: str) { // Traverse each character in the string + // If the node for this character doesn't exist, create it + if (node->v[i - 'a'] == NULL) { + node->v[i - 'a'] = new trie(); // Create a new Trie node + node = node->v[i - 'a']; // Move to the newly created node + node->x = node->x + 1; // Increment the count for this prefix + } else { + node = node->v[i - 'a']; // Move to the existing node + node->x = node->x + 1; // Increment the count for this prefix + } + } +} + +// Function to calculate the sum of prefix scores for a given string +void solve(string str, trie* node, int &x) { + trie* p = node; // Pointer to traverse the Trie + for (auto &i: str) { // Traverse each character in the string + p = p->v[i - 'a']; // Move to the next node in the Trie + x += p->x; // Add the count of this prefix to the total score + } +} + +// Main solution class +class Solution { +public: + // Function to calculate sum of prefix scores for all words + vector sumPrefixScores(vector& words) { + trie *node = new trie(); // Create the root node of the Trie + + // Step 1: Insert each word into the Trie and build the prefix tree + for (auto &i: words) { + maketrie(i, node); // Insert word into the Trie + } + + vector ans; // Vector to store the final prefix scores + int x = 0; // Variable to store the current score for a word + + // Step 2: Calculate the prefix score for each word + for (auto &i: words) { + x = 0; // Reset the score for the new word + solve(i, node, x); // Calculate the prefix score for the current word + ans.push_back(x); // Store the score in the answer vector + } + + return ans; // Return the final list of prefix scores + } +};