InterviewDB Experience

Text Rewrite: Replace Words Using a Substitution Dictionary

Interview Experience

Problem

Given a sentence and a dictionary mapping words to their replacements, rewrite the sentence by substituting every occurrence of a dictionary key with its value. Matching is case-insensitive but preserve the original casing pattern (all-caps, title-case, or lowercase) in the output.

python
def text_rewrite(sentence: str, substitutions: dict[str, str]) -> str:
    pass

def apply_case(original: str, replacement: str) -> str:
    """Match the case pattern of original in the replacement string."""
    pass

**Input**:
  sentence = "The Quick BROWN fox jumps"
  substitutions = {"quick": "slow", "brown": "red", "fox": "cat"}

**Output**: "The Slow RED cat jumps"
# "Quick" -> title case -> "Slow"
# "BROWN" -> all caps -> "RED"
# "fox" -> lowercase -> "cat"

Follow-ups

  1. How do you handle substitutions where the replacement is a multi-word phrase and case patterns differ per word?
  2. What if dictionary keys overlap (e.g., "cat" and "catch")? Define a disambiguation rule.
  3. How would you process a file too large to fit in memory?
  4. Extend to support regex-based substitution patterns in the dictionary keys.

Full Details

Problem

Given a sentence and a dictionary mapping words to their replacements, rewrite the sentence by substituting every occurrence of a dictionary key with its value. Matching is case-insensitive but preserve the original casing pattern (all-caps, title-case, or lowercase) in the output.

python
def text_rewrite(sentence: str, substitutions: dict[str, str]) -> str:
    pass

def apply_case(original: str, replacement: str) -> str:
    """Match the case pattern of original in the replacement string."""
    pass

**Input**:
  sentence = "The Quick BROWN fox jumps"
  substitutions = {"quick": "slow", "brown": "red", "fox": "cat"}

**Output**: "The Slow RED cat jumps"
# "Quick" -> title case -> "Slow"
# "BROWN" -> all caps -> "RED"
# "fox" -> lowercase -> "cat"

Follow-ups

  1. How do you handle substitutions where the replacement is a multi-word phrase and case patterns differ per word?
  2. What if dictionary keys overlap (e.g., "cat" and "catch")? Define a disambiguation rule.
  3. How would you process a file too large to fit in memory?
  4. Extend to support regex-based substitution patterns in the dictionary keys.

About This Question

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

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