Construct Smallest Number From DI String

medium greedy stack string

Problem

Given a pattern of length n made of 'I' (increasing) and 'D' (decreasing), build a string num of length n + 1 using digits '1'..'9' each at most once, where num[i] < num[i+1] when pattern[i] is 'I' and num[i] > num[i+1] when pattern[i] is 'D'. Return the lexicographically smallest valid num.

Inputpattern = "IIIDIDDD"
Output"123549876"
Increasing at indices 0,1,2,4 and decreasing at 3,5,6,7; this is the smallest such number.
Inputpattern = "DDD"
Output"4321"
Four positions, all decreasing, so the smallest run of consecutive digits is 4,3,2,1.

def smallest_number(pattern):
    n = len(pattern)
    result, stack = [], []
    for i in range(n + 1):
        stack.append(str(i + 1))
        if i == n or pattern[i] == 'I':
            while stack:
                result.append(stack.pop())
    return ''.join(result)
function smallestNumber(pattern) {
  const n = pattern.length;
  const result = [], stack = [];
  for (let i = 0; i <= n; i++) {
    stack.push(String(i + 1));
    if (i === n || pattern[i] === 'I') {
      while (stack.length) result.push(stack.pop());
    }
  }
  return result.join('');
}
String smallestNumber(String pattern) {
    int n = pattern.length();
    StringBuilder result = new StringBuilder();
    Deque<Character> stack = new ArrayDeque<>();
    for (int i = 0; i <= n; i++) {
        stack.push((char) ('1' + i));
        if (i == n || pattern.charAt(i) == 'I') {
            while (!stack.isEmpty()) result.append(stack.pop());
        }
    }
    return result.toString();
}
string smallestNumber(string pattern) {
    int n = pattern.size();
    string result;
    stack<char> st;
    for (int i = 0; i <= n; i++) {
        st.push((char)('1' + i));
        if (i == n || pattern[i] == 'I') {
            while (!st.empty()) { result += st.top(); st.pop(); }
        }
    }
    return result;
}
Time: O(n) Space: O(n)