↓Skip to main content
  1. LeetCode/

LeetCode 2416: Sum of Prefix Scores of Strings

·2 mins· ·
LeetCode Hard Trie String Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-09-13

  • Submissions: Accepted (first try)

Approach
#

A prefix’s score is the number of words that start with it. Each word’s answer is the sum of the scores of all its prefixes.

In a Trie, each node represents a prefix, and “words starting with it” means “words passing through this node”. So:

  1. While building the Trie, increment the count of every node a word passes through.
  2. Walk each word through the Trie again and add up the counts along the way.

My Solution
#

class Solution:
    def sumPrefixScores(self, words: List[str]) -> List[int]:
        trie = {}                          # char -> [pass count, children]
        for word in words:
            node = trie
            for ch in word:
                if ch not in node:
                    node[ch] = [0, {}]
                node[ch][0] += 1
                node = node[ch][1]

        res = []
        for word in words:
            total, node = 0, trie
            for ch in word:
                total += node[ch][0]
                node = node[ch][1]
            res.append(total)
        return res

Complexity
#

Time O(total length): one pass to build and one to query. Space O(total length).

My submission used 293MB of memory: every node is [count, dict], and small Python dicts carry a fixed overhead. A class with __slots__ would save some.

Mistakes to Avoid
#

  • Rescanning all words for every prefix: O(n · L^2) or worse, too slow.
  • Incrementing only when a child node is created instead of on every pass: repeated prefixes get undercounted.

Interview Explanation
#

Each Trie node represents a prefix, and the number of words starting with that prefix is the number of words passing through the node. So while building the Trie I increment the count on every node a word passes, and then each word walks the Trie again and sums the counts along its path. Building and querying are both linear in the total length.

Related

LeetCode 2781: Length of the Longest Valid Substring
·3 mins
LeetCode Hard Sliding-Window Hash-Table String Trie
LeetCode 2781 note: forbidden words are at most 10 long, so each right end checks only the last 10 suffixes; on a match push the left end past it, using the shortest match (the rightmost start)
LeetCode 3518: Smallest Palindromic Rearrangement II
·3 mins
LeetCode Hard Math Combinatorics Counting Hash-Table String
LeetCode 3518 note: a palindrome is determined by its left half, so this is the k-th permutation of a multiset; try characters position by position and use permutation counts, updated in O(1), to find k’s branch
LeetCode 940: Distinct Subsequences II
·2 mins
LeetCode Hard Dynamic-Programming String
LeetCode 940 note: group by last character; distinct subsequences ending with c = every current distinct subsequence with c appended, plus c itself, replacing the old value
LeetCode 1178: Number of Valid Words for Each Puzzle
·3 mins
LeetCode Hard Bit-Manipulation Hash-Map Trie
LeetCode 1178 note: a word only matters by its set of letters, so count 26-bit masks and enumerate each puzzle’s submasks
LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers
·2 mins
LeetCode Hard Dynamic-Programming State-Machine String
LeetCode 1320 note: after typing word[i], one finger is always on word[i], so the state is only the other finger’s position; dp[other] is the least distance with the other finger at other
LeetCode 902: Numbers At Most N Given Digit Set
·2 mins
LeetCode Hard Dynamic-Programming Digit-Dp Math Binary-Search String
LeetCode 902 note: digit DP with state (pos, tight, started); before starting, a position can be skipped, representing numbers with fewer digits than n