You are given a replacements mapping and a text string that may contain placeholders formatted as %var%, where each var corresponds to a key in the replacements mapping.

Each replacement value may itself contain one or more such placeholders. Each placeholder is replaced by the value associated with its corresponding replacement key.

Return the fully substituted text string which does not contain any placeholders.

Input & Output

Example 1 — Basic Substitution
$ Input: replacements = {"name": "John", "place": "NYC"}, text = "Hello %name%, welcome to %place%!"
Output: "Hello John, welcome to NYC!"
💡 Note: Direct substitution: %name% becomes "John" and %place% becomes "NYC"
Example 2 — Nested Placeholders
$ Input: replacements = {"name": "Alice", "greeting": "Hi %name%!"}, text = "%greeting% How are you?"
Output: "Hi Alice! How are you?"
💡 Note: First %greeting% becomes "Hi %name%!", then %name% becomes "Alice"
Example 3 — No Replacements Needed
$ Input: replacements = {"name": "Bob"}, text = "Hello world!"
Output: "Hello world!"
💡 Note: Text contains no placeholders, so it remains unchanged

Constraints

  • 1 ≤ replacements.length ≤ 100
  • 1 ≤ text.length ≤ 1000
  • All replacement keys and values contain only alphanumeric characters
  • No circular dependencies in replacement values

Visualization

Tap to expand
Apply Substitutions - Dependency Resolution DFS INPUT replacements "name" --> "John" "place" --> "NYC" text "Hello %name%, welcome to %place%!" Placeholders to resolve: %name% %place% ALGORITHM STEPS 1 Find Placeholders Scan text for %var% pattern 2 DFS Resolution Resolve nested dependencies 3 Lookup Values Get value from replacements 4 Substitute Replace placeholder with value Resolution Process %name% --> John OK %place% --> NYC OK No nested deps - direct resolve FINAL RESULT Before: "Hello %name%, welcome to %place%!" After: "Hello John, welcome to NYC!" Output String: Hello John, welcome to NYC! All Resolved OK Key Insight: DFS is used because replacement values may contain nested placeholders that need recursive resolution. The algorithm builds a dependency graph and resolves in topological order, caching results to avoid redundant work. TutorialsPoint - Apply Substitutions | Dependency Resolution DFS
Asked in
Google 15 Microsoft 12 Amazon 8
12.4K Views
Medium Frequency
~15 min Avg. Time
487 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