2416. Sum of Prefix Scores of Strings #609
-
Topics: You are given an array We define the score of a string
Return an array Note that a string is considered as a prefix of itself. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a Trie data structure, which is particularly efficient for working with prefixes. Each node in the Trie will represent a letter of the words, and we'll maintain a counter at each node to store how many times that prefix has been encountered. This allows us to efficiently calculate the score of each prefix by counting how many words start with that prefix. Approach:
Let's implement this solution in PHP: 2416. Sum of Prefix Scores of Strings <?php
class TrieNode {
/**
* @var array
*/
public $children;
/**
* @var int
*/
public $count;
public function __construct() {
$this->children = [];
$this->count = 0;
}
}
class Trie {
/**
* @var TrieNode
*/
private $root;
public function __construct() {
$this->root = new TrieNode();
}
/**
* Insert a word into the Trie and update the prefix counts
*
* @param $word
* @return void
*/
public function insert($word) {
$node = $this->root;
foreach (str_split($word) as $char) {
if (!isset($node->children[$char])) {
$node->children[$char] = new TrieNode();
}
$node = $node->children[$char];
$node->count++; // Increase the count at this node
}
}
/**
* Get the sum of prefix scores for a given word
*
* @param $word
* @return int
*/
public function getPrefixScores($word) {
$node = $this->root;
$prefixScore = 0;
foreach (str_split($word) as $char) {
if (!isset($node->children[$char])) {
break;
}
$node = $node->children[$char];
$prefixScore += $node->count;
}
return $prefixScore;
}
}
/**
* @param String[] $words
* @return Integer[]
*/
function sumOfPrefixScores($words) {
$trie = new Trie();
// Step 1: Insert all words into the Trie
foreach ($words as $word) {
$trie->insert($word);
}
// Step 2: Calculate prefix scores for each word
$result = [];
foreach ($words as $word) {
$result[] = $trie->getPrefixScores($word);
}
return $result;
}
// Example usage:
$words1 = ["abc", "ab", "bc", "b"];
$words2 = ["abcd"];
print_r(sumOfPrefixScores($words1)); // Output: [5, 4, 3, 2]
print_r(sumOfPrefixScores($words2)); // Output: [4]
?> Explanation:
Example:For
Time Complexity:
This approach ensures that we efficiently compute the prefix scores in linear time relative to the total number of characters in all words. |
Beta Was this translation helpful? Give feedback.
We can use a Trie data structure, which is particularly efficient for working with prefixes. Each node in the Trie will represent a letter of the words, and we'll maintain a counter at each node to store how many times that prefix has been encountered. This allows us to efficiently calculate the score of each prefix by counting how many words start with that prefix.
Approach:
Insert Words into Trie:
Calculate Prefix Scores: