KatInterview

760. Bold Words in String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all occurrences of a set of keywords in a given string s and make them bold. The key constraints are that overlapping or adjacent bold segments must be merged into a single bold segment to use the minimum number of HTML `` tags.

Solution

Bold Words in String in Python

class Solution:
    def boldWords(self, words: List[str], s: str) -> str:
        n = len(s)
        if n == 0:
            return ""
        
        # Step 1: Create a boolean array to mark bold characters.
        bold = [False] * n
        for word in words:
            start = s.find(word)
            while start != -1:
                # Mark the interval corresponding to the found word as bold.
                for i in range(start, start + len(word)):
                    bold[i] = True
                # Search for the next occurrence.
                start = s.find(word, start + 1)
        
        # Step 2: Build the result string with bold tags.
        res = []
        for i in range(n):
            # Add opening tag <b> if it's the start of a bold section.
            if bold[i] and (i == 0 or not bold[i - 1]):
                res.append("<b>")
            
            res.append(s[i])
            
            # Add closing tag </b> if it's the end of a bold section.
            if bold[i] and (i == n - 1 or not bold[i + 1]):
                res.append("</b>")
                
        return "".join(res)

Bold Words in String in Java

class Solution {
    public String boldWords(String[] words, String s) {
        int n = s.length();
        if (n == 0) {
            return "";
        }
        
        // Step 1: Create a boolean array to mark bold characters.
        boolean[] bold = new boolean[n];
        for (String word : words) {
            int index = s.indexOf(word, 0);
            while (index != -1) {
                // Mark the interval corresponding to the found word as bold.
                for (int i = index; i < index + word.length(); i++) {
                    bold[i] = true;
                }
                // Search for the next occurrence.
                index = s.indexOf(word, index + 1);
            }
        }
        
        // Step 2: Build the result string with bold tags.
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < n; i++) {
            // Add opening tag <b> if it's the start of a bold section.
            if (bold[i] && (i == 0 || !bold[i - 1])) {
                result.append("<b>");
            }
            
            result.append(s.charAt(i));
            
            // Add closing tag </b> if it's the end of a bold section.
            if (bold[i] && (i == n - 1 || !bold[i + 1])) {
                result.append("</b>");
            }
        }
        
        return result.toString();
    }
}

Bold Words in String in C++

class Solution {
public:
    string boldWords(vector<string>& words, string s) {
        int n = s.length();
        if (n == 0) {
            return "";
        }
        
        // Step 1: Create a boolean array to mark bold characters.
        vector<bool> bold(n, false);
        for (const string& word : words) {
            size_t pos = s.find(word, 0);
            while (pos != string::npos) {
                // Mark the interval corresponding to the found word as bold.
                for (int i = pos; i < pos + word.length(); ++i) {
                    bold[i] = true;
                }
                // Search for the next occurrence.
                pos = s.find(word, pos + 1);
            }
        }
        
        // Step 2: Build the result string with bold tags.
        string result = "";
        for (int i = 0; i < n; ++i) {
            // Add opening tag <b> if it's the start of a bold section.
            if (bold[i] && (i == 0 || !bold[i - 1])) {
                result += "<b>";
            }
            
            result += s[i];
            
            // Add closing tag </b> if it's the end of a bold section.
            if (bold[i] && (i == n - 1 || !bold[i + 1])) {
                result += "</b>";
            }
        }
        
        return result;
    }
};

Bold Words in String in TypeScript

function boldWords(words: string[], s: string): string {
    const n = s.length;
    if (n === 0) {
        return "";
    }

    // Step 1: Create a boolean array to mark bold characters.
    const bold = new Array(n).fill(false);
    for (const word of words) {
        let index = s.indexOf(word);
        while (index !== -1) {
            // Mark the interval corresponding to the found word as bold.
            for (let i = index; i < index + word.length; i++) {
                bold[i] = true;
            }
            // Search for the next occurrence.
            index = s.indexOf(word, index + 1);
        }
    }

    // Step 2: Build the result string with bold tags.
    let result = "";
    for (let i = 0; i < n; i++) {
        // Add opening tag <b> if it's the start of a bold section.
        if (bold[i] && (i === 0 || !bold[i - 1])) {
            result += "<b>";
        }

        result += s[i];

        // Add closing tag </b> if it's the end of a bold section.
        if (bold[i] && (i === n - 1 || !bold[i + 1])) {
            result += "</b>";
        }
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.