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

# DI String Match Python Solution with Tests

> Tested Python solution for LeetCode 942 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 942, [Easy](/catalog/easy). Topics: [Array](/catalog/topics/array), [Two Pointers](/catalog/topics/two-pointers), [String](/catalog/topics/string), [Greedy](/catalog/topics/greedy). [View on LeetCode](https://leetcode.com/problems/di-string-match/description/).

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

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

## Problem

A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:

* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.

Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations `perm`, return **any of them**.

### Examples

```
Input: s = "IDID"
Output: [0,4,1,3,2]
Explanation: [0,4,1,3,2] is one valid answer.
```

```
Input: s = "III"
Output: [0,1,2,3]
```

```
Input: s = "DDI"
Output: [3,2,0,1]
```

### Constraints

* `1 <= s.length <= 10^5`
* `s[i]` is either `'I'` or `'D'`.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n) for the output
    def di_string_match(self, s: str) -> list[int]:
        low, high = 0, len(s)
        perm: list[int] = []
        for char in s:
            if char == "I":
                perm.append(low)
                low += 1
            else:
                perm.append(high)
                high -= 1
        perm.append(low)
        return perm
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) for the output |

## Tags


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