> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Apply Substitutions Python Solution with Tests

> Tested Python solution for LeetCode 3481 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 3481, [Medium](/catalog/medium). Topics: [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Graph](/catalog/topics/graph), [Topological Sort](/catalog/topics/topological-sort), [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/apply-substitutions/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 3481   # by problem number
lcpy gen -s apply_substitutions   # by problem name
```

## Problem

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**.

### Examples

```
Input: replacements = [["A","abc"],["B","def"]], text = "%A%_%B%"
Output: "abc_def"
Explanation: Replace %A% with "abc" and %B% with "def". The final text becomes "abc_def".
```

```
Input: replacements = [["A","bce"],["B","ace"],["C","abc%B%"]], text = "%A%_%B%_%C%"
Output: "bce_ace_abcace"
Explanation: Replace %A% with "bce" and %B% with "ace". Then substitute %B% in "abc%B%" with "ace" to obtain "abcace". The final text becomes "bce_ace_abcace".
```

### Constraints

* `1 <= replacements.length <= 10`
* Each element of `replacements` is a two-element list `[key, value]`, where:
  * `key` is a single uppercase English letter.
  * `value` is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as `%<key>%`.
* All replacement keys are unique.
* The `text` string is formed by concatenating all key placeholders (formatted as `%<key>%`) randomly from the replacements mapping, separated by underscores.
* `text.length == 4 * replacements.length - 1`
* Every placeholder in the `text` or in any replacement value corresponds to a key in the `replacements` mapping.
* There are no cyclic dependencies between replacement keys.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/apply_substitutions/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/apply_substitutions/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(m + n * L) where m is total mapping size, L the average substituted length
    # Space: O(m + n * L)
    def apply_substitutions(self, replacements: list[list[str]], text: str) -> str:
        values: dict[str, str] = dict(replacements)

        def dfs(s: str) -> str:
            i = s.find("%")
            if i == -1:
                return s
            j = s.find("%", i + 1)
            if j == -1:
                return s
            key = s[i + 1 : j]
            return s[:i] + dfs(values[key]) + dfs(s[j + 1 :])

        return dfs(text)
```

## Complexity

| Time | Space |
| - | - |
| O(m + n \* L) where m is total mapping size, L the average substituted length | O(m + n \* L) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.