# Construct the Smallest Number From DI String

# 2375. Construct the Smallest Number From DI String

You are given a 0-indexed string pattern of length n consisting of the characters ‘I’ meaning increasing and ‘D’ meaning decreasing.

A 0-indexed string num of length n + 1 is created using the following conditions:

num consists of the digits ‘1’ to ‘9’, where each digit is used at most once.
If pattern[i] == ‘I’, then num[i] < num[i + 1]. If pattern[i] == 'D', then num[i] > num[i + 1].
Return the lexicographically smallest possible string num that meets the conditions.

```### Example 1:
```
Input: pattern = "IIIDIDDD"
Output: "123549876"
Explanation:
At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].
At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].
Some possible values of num are "245639871", "135749862", and "123849765".
It can be proven that "123549876" is the smallest possible num that meets the conditions.
Note that "123414321" is not possible because the digit '1' is used more than once.
```
```
```### Example 2:
```
Input: pattern = "DDD"
Output: "4321"
Explanation:
Some possible values of num are "9876", "7321", and "8742".
It can be proven that "4321" is the smallest possible num that meets the conditions.
```
```
```Constraints:
```
1 <= pattern.length <= 8
pattern consists of only the letters 'I' and 'D'.
```
```
```/**
* @param {string} pattern
* @return {string}
*/
var smallestNumber = function(pattern) {
const out = [];
let stack = [];
const len = pattern.length;

for (let i = 0; i <= len; i++) {
stack.push(i + 1);
if (pattern[i] == 'I' || i == len) {
out.push(...stack.reverse());
stack = [];
}
}
return out.join('');
};
```
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://upokary.com/construct-the-smallest-number-from-di-string/", "fetch_time": 1723239258000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-33/segments/1722640782236.55/warc/CC-MAIN-20240809204446-20240809234446-00386.warc.gz", "warc_record_offset": 458758994, "warc_record_length": 12156, "token_count": 484, "char_count": 1693, "score": 3.5, "int_score": 4, "crawl": "CC-MAIN-2024-33", "snapshot_type": "latest", "language": "en", "language_score": 0.7397464513778687, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00042-of-00064.parquet"}