InterviewDB Experience

Highlight Letters: Find and Mark Matching Characters in a String for Search Highlighting

Interview Experience

Round 1 Coding

Problem

Given a source string and a query,

return the source string with matching characters wrapped in highlight markers. Match the query characters in order (subsequence match, not substring).

Return the highlighted string and a match score (bonus for consecutive matches).

python
def highlight(source: str, query: str,
              open_tag: str = "[", close_tag: str = "]") -> tuple[str, int]:

**returns** (highlighted_string, score)
    # score = len(query) base + bonus for each run of consecutive matches

**returns** ("", -1) if no subsequence match
    ...

Example

highlight("Python", "Pto")
# Match P(0), t(2), o(4) as subsequence
# -> ("[P]y[t]h[o]n", 3)

highlight("Python", "Pyt")
# Match P(0),y(1),t(2) -> consecutive run of 3 -> bonus
# -> ("[Pyt]hon", 6)  # score 3 base + 3 consecutive bonus

highlight("Python", "xyz")
# -> ("", -1)  # no match

Follow-ups

  1. How does your scoring affect the ranking of multiple candidate strings for the same query?
  2. How do you make matching case-insensitive while preserving the original casing in output?
  3. How would you extend this to a fuzzy match that allows one character substitution?
  4. Given a list of 10,000 filenames, how do you efficiently rank them by match score for a query?

Full Details

Round 1 Coding

Problem

Given a source string and a query,

return the source string with matching characters wrapped in highlight markers. Match the query characters in order (subsequence match, not substring).

Return the highlighted string and a match score (bonus for consecutive matches).

python
def highlight(source: str, query: str,
              open_tag: str = "[", close_tag: str = "]") -> tuple[str, int]:

**returns** (highlighted_string, score)
    # score = len(query) base + bonus for each run of consecutive matches

**returns** ("", -1) if no subsequence match
    ...

Example

highlight("Python", "Pto")
# Match P(0), t(2), o(4) as subsequence
# -> ("[P]y[t]h[o]n", 3)

highlight("Python", "Pyt")
# Match P(0),y(1),t(2) -> consecutive run of 3 -> bonus
# -> ("[Pyt]hon", 6)  # score 3 base + 3 consecutive bonus

highlight("Python", "xyz")
# -> ("", -1)  # no match

Follow-ups

  1. How does your scoring affect the ranking of multiple candidate strings for the same query?
  2. How do you make matching case-insensitive while preserving the original casing in output?
  3. How would you extend this to a fuzzy match that allows one character substitution?
  4. Given a list of 10,000 filenames, how do you efficiently rank them by match score for a query?

About This Question

This is a candidate experience report from a retool interview during the phone round.

It covers the following topics: Coding, Phone, Strings .