Template String Interpolator

Difficulty: Medium · Topics: String Parsing, Map, Regex

Difficulty: Medium  |  Tags: String Parsing, Map, Regex

Description

Given a template string containing ${variable} placeholders and a map of values, replace all placeholders with their corresponding values.

Implement:

interpolate(template, values) → String

Examples

Example 1:

Input:
  template = "Hello, ${name}! Welcome to ${city}."
  values   = {"name": "Alice", "city": "NYC"}

Output: "Hello, Alice! Welcome to NYC."

Example 2 — Missing key:

Input:
  template = "Order #${orderId} — ${status}"
  values   = {"orderId": "12345"}

Output: "Order #12345 — ${status}"
Explanation: Missing keys remain as-is.

Example 3 — Nested resolution:

Input:
  template = "${greeting}, ${name}!"
  values   = {"greeting": "Hi", "name": "Bob"}

Output: "Hi, Bob!"

Example 4 — Escaped:

Input:
  template = "Use \\${variable} for placeholders. Value: ${x}"
  values   = {"x": "42"}

Output: "Use ${variable} for placeholders. Value: 42"

Constraints

Practice this problem

Related problems