Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Sum of Prefix Scores of Strings

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2416" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an array words of size n consisting of non-empty strings. We define the score of a string term as the number of strings words[i] such that term is a prefix of words[i]. For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i]. Note that a string is considered as a prefix of itself. Example 1: Input: words = ["abc","ab","bc","b"] Output: [5,4,3,2] Explanation: The answer for each string is the following: - "abc" has 3 prefixes: "a", "ab", and "abc". - There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc". The total is answer[0] = 2 + 2 + 1 = 5. - "ab" has 2 prefixes: "a" and "ab". - There are 2 strings with the prefix "a", and 2 strings with the prefix "ab". The total is answer[1] = 2 + 2 = 4. - "bc" has 2 prefixes: "b" and "bc". - There are 2 strings with the prefix "b", and 1 string with the prefix "bc". The total is answer[2] = 2 + 1 = 3. - "b" has 1 prefix: "b". - There are 2 strings with the prefix "b". The total is answer[3] = 2. Example 2: Input: words = ["abcd"] Output: [4] Explanation: "abcd" has 4 prefixes: "a", "ab", "abc", and "abcd". Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4. Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists of lowercase English letters.

Explanation

Here's a breakdown of the approach and the Python code:

  • Trie Data Structure: Construct a Trie (prefix tree) to efficiently store and count prefixes. Each node in the Trie will store the count of words that have the path from the root to that node as a prefix.

  • Prefix Sum Calculation: Iterate through the input words. For each word, generate its prefixes. Look up the count associated with each prefix in the Trie, and sum these counts to get the final score for that word.

  • Optimization: The Trie structure enables efficient prefix counting, avoiding repeated linear searches through the words array for each prefix.

  • Complexity:

    • Runtime: O(N * M), where N is the number of words and M is the maximum length of a word. This is because we iterate through each word and, in the worst case, iterate up to the length of the word to build prefixes and traverse the Trie.
    • Storage: O(N * M) in the worst case, as the Trie could potentially store all prefixes of all words.

Code

    class TrieNode:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
            node.count += 1

    def get_count(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return 0
            node = node.children[char]
        return node.count

def sumPrefixScores(words):
    trie = Trie()
    for word in words:
        trie.insert(word)

    result = []
    for word in words:
        score = 0
        for i in range(1, len(word) + 1):
            prefix = word[:i]
            score += trie.get_count(prefix)
        result.append(score)

    return result

More from this blog

C

Chatmagic blog

2894 posts