> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Bold Words in String Python Solution

> Tested Python solution for LeetCode 758 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 758, [Medium](/catalog/medium). Topics: [Trie](/catalog/topics/trie), [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string), [String Matching](/catalog/topics/string-matching). [View on LeetCode](https://leetcode.com/problems/bold-words-in-string/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 758   # by problem number
lcpy gen -s bold_words_in_string   # by problem name
```

## 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.

Return `s` *after adding the bold tags*. The returned string should use the least number of tags possible, and the tags should form a valid combination.

### Examples

```
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.
```

```
Input: words = ["ab","cb"], s = "aabcd"
Output: "a<b>ab</b>cd"
```

### Constraints

* `1 <= s.length <= 500`
* `0 <= words.length <= 50`
* `1 <= words[i].length <= 10`
* `s` and `words[i]` consist of lowercase English letters.

**Note:** This question is the same as [616: Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/description/).

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bold_words_in_string/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/bold_words_in_string/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Trie:
    def __init__(self) -> None:
        self.children: dict[str, Trie] = {}
        self.is_end = False

    def insert(self, word: str) -> None:
        node = self
        for ch in word:
            if ch not in node.children:
                node.children[ch] = Trie()
            node = node.children[ch]
        node.is_end = True


class Solution:
    # Time: O(total keyword chars + n * max keyword length + n)
    # Space: O(total keyword chars + n)
    def bold_words(self, words: list[str], s: str) -> str:
        trie = Trie()
        for word in words:
            trie.insert(word)

        n = len(s)
        intervals: list[list[int]] = []
        for i in range(n):
            node = trie
            for j in range(i, n):
                nxt = node.children.get(s[j])
                if nxt is None:
                    break
                node = nxt
                if node.is_end:
                    if intervals and intervals[-1][1] + 1 >= i:
                        intervals[-1][1] = max(intervals[-1][1], j)
                    else:
                        intervals.append([i, j])

        parts: list[str] = []
        prev = 0
        for start, end in intervals:
            parts.append(s[prev:start])
            parts.append("<b>")
            parts.append(s[start : end + 1])
            parts.append("</b>")
            prev = end + 1
        parts.append(s[prev:])
        return "".join(parts)
```

## Complexity

| Time | Space |
| - | - |
| O(total keyword chars + n \* max keyword length + n) | O(total keyword chars + n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.