Problem · String

Template Variable Expansion

Learn this problem
MediumGoogleONSITE INTERVIEW
See Google hiring insights

Problem statement

You are given key-value mappings and a source string. Any substring inside a pair of percent signs, such as %key%, should be treated as a key and replaced by its mapped value.

A mapped value may itself contain another key placeholder, so replacements may need to be resolved recursively.

If a referenced key is missing, or if resolving placeholders finds a cycle, return "ERROR".

Function

expandTemplate(mappings: String[][], source: String) → String

Examples

Example 1

mappings = [["x","%y%/home"],["y","user"]]source = "/%x%/docs"return = "/user/home/docs"

%x% expands to %y%/home, and %y% expands to user.

The source shared the rule but did not include this exact sample. FastPrep added this small example so the behavior can be checked directly.

More Google problems

drafts saved locally
public String expandTemplate(String[][] mappings, String source) {
  // write your code here
}
mappings[["x","%y%/home"],["y","user"]]
source"/%x%/docs"
expected"/user/home/docs"
checking account