Problem · String
Template Variable Expansion
Learn this problemProblem 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) → StringExamples
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
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026