DI String Match Problem
Description
LeetCode Problem 942.
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.
Example 1:
Input: s = "IDID"
Output: [0,4,1,3,2]
Example 2:
Input: s = "III"
Output: [0,1,2,3]
Example 3:
Input: s = "DDI"
Output: [3,2,0,1]
Constraints:
- 1 <= s.length <= 10^5
- s[i] is either 'I' or 'D'.
Solution
Approach: Greedy From Both Ends
Keep two numbers: low, the smallest number not used yet, and high, the largest. They start at 0 and n.
Go through s from left to right:
- On
'I', placelowand increase it. Every number still unused is larger than the one just placed, so whatever comes next is guaranteed to be bigger. - On
'D', placehighand decrease it. Every number still unused is smaller, so whatever comes next is guaranteed to be smaller.
After all n letters, low and high meet at the one remaining number, which goes in the last position.
Why this always works: the condition s[i] is about perm[i] and perm[i + 1], and the next number has not been chosen yet when we place perm[i]. By placing the extreme value, we make the condition true no matter which unused number ends up at perm[i + 1]. Each value is used once because low only rises and high only falls.
The step that is easy to miss is the last element: the loop runs n times but the permutation has n + 1 numbers.
For s = "IDID": I places 0, D places 4, I places 1, D places 3, and 2 is left: [0,4,1,3,2].
Complexity: O(n) time and O(1) extra space besides the output, where n is the length of s.
class Solution:
def diStringMatch(self, s: str) -> List[int]:
low, high = 0, len(s) # smallest and largest numbers not used yet
perm = []
for ch in s:
if ch == "I":
# Anything left is larger than low, so the next step can only go up.
perm.append(low)
low += 1
else:
# Anything left is smaller than high, so the next step can only go down.
perm.append(high)
high -= 1
perm.append(low) # low == high: the one number left
return perm