1198. Placeholder Fill

Medium3.5 points estimatedStringHash Table

A newsletter tool fills templates. Replace each {name} in text with its value from pairs, where each entry is "name=value" split at the first =. If a name appears in several pairs the later one wins, and an unknown name becomes ?.

The doubled braces {{ and }} produce a literal { and }. Scan left to right: at a {, if the next character is also { emit one brace and skip both, otherwise read up to the next } as a name. Every single { opens a well-formed placeholder, names are letters and digits, and values contain no braces.

Build a map from the pairs, then one pass over the text gives O(n + total pair length) time and O(n) space.

Example 1

Input:
text = "Hello, {name}!", pairs = ["name=Ada"]
Output:
"Hello, Ada!"
Explanation:

The placeholder name is replaced by Ada.

Example 2

Input:
text = "{a}{b}{a}", pairs = ["a=1","b=2","a=3"]
Output:
"323"
Explanation:

The later pair overrides a, so a is 3 and the result is 323.

Example 3

Input:
text = "{{x}} {x}", pairs = ["x=5"]
Output:
"{x} 5"
Explanation:

The doubled braces give literal braces around x, and the single placeholder becomes 5.

Constraints

1 ≤ text.length ≤ 104

0 ≤ pairs.length ≤ 100

names are letters and digits; values contain no braces

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n + P)
Space
O(n + P)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…