Find Permutation Problem
Description
LeetCode Problem 484.
A permutation perm of n integers of all the integers in the range [1, n] can be represented as a string s of length n - 1 where:
s[i] == 'I'ifperm[i] < perm[i + 1], ands[i] == 'D'ifperm[i] > perm[i + 1].
Given a string s, reconstruct the lexicographically smallest permutation perm and return it.
Example 1:
Input: s = "I"
Output: [1,2]
Explanation: [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
Example 2:
Input: s = "DI"
Output: [2,1,3]
Explanation: Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
Constraints:
1 <= s.length <= 10^5s[i]is either'I'or'D'.
Solution
Approach: Reverse Each Run of D's
Without any 'D', the smallest permutation is simply 1, 2, ..., n (here n = s.length + 1). Each 'D' forces a descent, and we want to pay for it as late and as cheaply as possible.
Start from [1, 2, ..., n] and look at the maximal runs of consecutive 'D's. A run covering s[i..j-1] says perm[i] > perm[i+1] > ... > perm[j]: j - i + 1 positions in a row must decrease. Reversing the slice perm[i..j] turns those increasing numbers into a decreasing block, and it only uses the numbers that were already in that block. Everything before it stays exactly as small as before, and the 'I' on either side still holds: the block's numbers are all larger than what comes before and smaller than what comes after.
Why this is the smallest: at position i the block needs j - i smaller numbers after it, so perm[i] can be no smaller than the current smallest unused number plus j - i. Reversing puts exactly that number there, and then the rest of the block is forced. So the result is lexicographically minimal.
For s = "DI", the run of 'D' covers positions 0..1, so [1, 2, 3] becomes [2, 1, 3].
The tricky part is the index bookkeeping: the run s[i..j-1] affects j - i + 1 numbers, one more than its length, so the slice to reverse ends at j inclusive. After a run, continue from j (the next character is an 'I'); after an 'I', move one step.
Complexity: O(n) time, since every position is reversed at most once. O(1) extra space besides the answer.
class Solution:
def findPermutation(self, s: str) -> List[int]:
n = len(s)
ans = list(range(1, n + 2))
i = 0
while i < n:
# s[i:j] is a run of 'D's (possibly empty)
j = i
while j < n and s[j] == 'D':
j += 1
ans[i : j + 1] = ans[i : j + 1][::-1]
i = max(i + 1, j)
return ans