← Questions

Highlight categorized phrases in a review

0
AirbnbCodingLast asked Sep 2026

Reviews on a travel site should show key phrases with their category. Write a function that marks every mapped phrase in a review.

def highlight(review: str, mapping: list[tuple[str, str]]) -> str: ...

mapping is a list of (phrase, category) pairs. Return the review with each matched span replaced by [category]{matched_text}, where matched_text is the text exactly as it appears in the review.

Rules

  • Whole words only. Letters and digits are word characters; everything else, and the ends of the string, are boundaries. A match must start at the start of a word and end at the end of a word. For example, "pool" matches in "pool!" but not in "pools" or "carpool".
  • Case-insensitive. "wifi" matches "WiFi", and the output keeps WiFi.
  • Phrases can span words. "ocean view" matches "Ocean view". Spaces and punctuation inside a phrase must match exactly.
  • Longest match, left to right, no overlaps. Scan from the left. Where several phrases start at the same place, use the longest one. After a match, continue after it.
  • If the same phrase appears more than once in mapping, use the first category listed. Ignore empty phrases.

Constraints: review length up to 10^5; up to 10^4 phrases, each up to 100 characters.

Example 1

review  = "Great Ocean View, but the pool was cold."
mapping = [("ocean view", "scenery"), ("ocean", "nature"), ("pool", "amenity")]
output  = "Great [scenery]{Ocean View}, but the [amenity]{pool} was cold."

Example 2

review  = "Ocean breeze, no pools, carpool only."
mapping = [("ocean view", "scenery"), ("ocean", "nature"), ("pool", "amenity")]
output  = "[nature]{Ocean} breeze, no pools, carpool only."

"ocean view" does not fit, so the shorter "ocean" is used. "pools" and "carpool" are not whole-word matches.

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding