Template Engine - Problem

Build a simple template engine that replaces {{variable}} placeholders with provided values.

Given a template string containing placeholders in the format {{variableName}} and a dictionary of variable values, replace all placeholders with their corresponding values.

Requirements:

  • Replace all {{variableName}} with the value from the variables dictionary
  • If a variable is not found in the dictionary, leave the placeholder unchanged
  • Variable names can contain letters, numbers, and underscores
  • Nested braces like {{{var}}} should be handled correctly

Input & Output

Example 1 — Basic Template
$ Input: template = "Hello {{name}}, welcome to {{city}}!", variables = {"name": "Alice", "city": "Paris"}
Output: "Hello Alice, welcome to Paris!"
💡 Note: Both {{name}} and {{city}} are replaced with their corresponding values from the variables dictionary
Example 2 — Missing Variable
$ Input: template = "Hi {{name}}, your score is {{score}}", variables = {"name": "Bob"}
Output: "Hi Bob, your score is {{score}}"
💡 Note: {{name}} is replaced with 'Bob', but {{score}} remains unchanged since it's not in the variables dictionary
Example 3 — No Variables
$ Input: template = "Welcome to our website!", variables = {}
Output: "Welcome to our website!"
💡 Note: Template has no placeholders, so the original string is returned unchanged

Constraints

  • 1 ≤ template.length ≤ 1000
  • 0 ≤ variables.size() ≤ 100
  • Variable names contain only letters, numbers, and underscores
  • Variable values are strings

Visualization

Tap to expand
INPUTHello {{name}}, welcome!{{name}}Variables:{"name": "Alice","city": "Paris"}ALGORITHM STEPS1Scan Character by CharacterProcess template from left to right2Detect {{ PatternsWhen {{ found, collect variable name3Replace VariablesLook up in dictionary and substitute4Build Result StringContinue until template processedFINAL RESULTHello Alice, welcome!All {{variable}} placeholdersreplaced with actual valuesKey Insight:Single-pass character scanning with immediate variable replacementis more efficient than repeated string searching and replacement.TutorialsPoint - Template Engine | Single Pass Algorithm
Asked in
Google 25 Amazon 18 Microsoft 15
24.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen