Bold Words in String — LeetCode 758 Python Solution

MediumLeetCode PremiumTrieArrayHash TableStringString Matching
Problem
#758
Pattern
Trie
Reading time
10 min

The problem

Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between <b> and </b> tags become bold.

Example

Input
words = ["ab","bc"], s = "aabcd"
Output
"a<b>abc</b>d"
Explanation
Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.

Python solution

Python
class Trie:
    def __init__(self):
        self.children = [None] * 128
        self.is_end = False

    def insert(self, word):
        node = self
        for c in word:
            idx = ord(c)
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
        node.is_end = True


class Solution:
    def boldWords(self, words: List[str], s: str) -> str:
        trie = Trie()
        for w in words:
            trie.insert(w)
        n = len(s)
        pairs = []
        for i in range(n):
            node = trie
            for j in range(i, n):
                idx = ord(s[j])
                if node.children[idx] is None:
                    break
                node = node.children[idx]
                if node.is_end:
                    pairs.append([i, j])
        if not pairs:
            return s
        st, ed = pairs[0]
        t = []
        for a, b in pairs[1:]:
            if ed + 1 < a:
                t.append([st, ed])
                st, ed = a, b
            else:
                ed = max(ed, b)
        t.append([st, ed])

        ans = []
        i = j = 0
        while i < n:
            if j == len(t):
                ans.append(s[i:])
                break
            st, ed = t[j]
            if i < st:
                ans.append(s[i:st])
            ans.append('<b>')
            ans.append(s[st : ed + 1])
            ans.append('</b>')
            j += 1
            i = ed + 1

        return ''.join(ans)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 758. Bold Words in String is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 758. Bold Words in String?
LeetCode 758. Bold Words in String is rated Medium on LeetCode.
What is the time complexity of LeetCode 758. Bold Words in String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 758. Bold Words in String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 758. Bold Words in String cover?
LeetCode 758. Bold Words in String is tagged Trie, Array, Hash Table, String and String Matching on LeetCode.
Is LeetCode 758. Bold Words in String a premium problem?
Yes. LeetCode 758. Bold Words in String is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview