Google questions

Template Variable Expansion

GoogleOnsiteMedium

A template engine fills in %key% placeholders. Template(mappings) is built once from a list of [key, value] pairs. render(source) returns source with its placeholders filled in, or the string "ERROR" when it cannot. Every render call is independent: an "ERROR" result says nothing about later calls.

Part 1: Fill in placeholders

A placeholder is %key%: a %, the key, and a closing %. render(source) replaces every placeholder with the value stored for its key. Keys are case-sensitive.

Return "ERROR" when a key is not in the mappings, or when a % in source has no closing partner. A key is at least one character, so %% is an empty key, which is not in the mappings and gives "ERROR".

  1. Example 1
    init
    [[["user","ada"],["dir","docs"],["a","x"],["b","y"]]]
    operations
    [["render",["/home/%user%/%dir%/%user%.txt"]],["render",["no placeholders"]],["render",["%a%-%b%"]],["render",["%user%"]]]
    Output
    ["/home/ada/docs/ada.txt","no placeholders","x-y","ada"]

    Why: Each %key% is replaced by its value, and a key may appear more than once. A source with no placeholders is returned unchanged.

Constraints

  • 0 <= len(mappings) <= 100
  • 1 <= len(key) <= 20
  • keys are distinct and contain no %
  • 0 <= len(source) <= 1000
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Template Variable Expansion: Google interview question | LoopCoach