Problem Description
Given a string s composed only of the characters 'I' (for increasing) and 'D' (for decreasing), we need to reconstruct the lexicographically smallest permutation of the first n integers (where n = s.length + 1) such that:
- For every index i in s, if s[i] is 'I', then perm[i] < perm[i+1], and if s[i] is 'D', then perm[i] > perm[i+1].
Key Insights
- The answer is a permutation of numbers from 1 to n, where n = len(s) + 1.
- A common strategy is to use a stack to reverse the segments when a decrease ('D') is encountered.
- When an 'I' is encountered (or at the end), pop all numbers from the stack to output them in reverse order, ensuring the smallest lexicographical order.
- This greedy approach guarantees that as soon as a rising pattern is detected, we “flush” the pending decreases correctly.
Space and Time Complexity
Time Complexity: O(n) – Each element is pushed and popped exactly once. Space Complexity: O(n) – For the stack and the output array.
Solution
We use a greedy approach with a stack. Iterate from 0 to n (where n = len(s) + 1):
- Push the current number (i+1) onto the stack.
- If the current character is 'I' or we have reached the end of the string, pop all elements from the stack and append them to the result. By doing so, segments corresponding to series of 'D's are reversed, while 'I's trigger the flush, ensuring that the final permutation is the lexicographically smallest.