# DI String Match in Python

Suppose we have a string S that only contains "I" (to denote increase) or "D" (to denote decrease), let N = size of S. We have to return any permutation A of [0, 1, ..., N] such that for all i in range 0, ..., N-1 −

• If S[i] is "I", then A[i] < A[i+1]
• Otherwise when S[i] is "D", then A[i] > A[i+1]

So, if the input is like "IDID", then the output will be [0,4,1,3,2]

To solve this, we will follow these steps −

• A := a list from 0 to N where N is the size of S.
• res = a blank list
• for each element j in S, do
• if j is I, then delete last element from A and insert into res
• otherwise delete first element of A and insert into res
• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def diStringMatch(self, S):
A=[i for i in range(len(S)+1)]
return [A.pop((j=='I')-1) for j in S]+A
ob = Solution()
print(ob.diStringMatch("IDID"))

## Input

"IDID"

## Output

[0, 4, 1, 3, 2]

Advertisements