Generate a sequence with the given operations

Given a string S which contains only I (increase) and D (decrease). The task is to return any permutation of integers [0, 1, …, N] where N ≤ Length of S such that for all i = 0, …, N-1:

  1. If S[i] == “D”, then A[i] > A[i+1]
  2. If S[i] == “I”, then A[i] < A[i+1].

Note that output must contain distinct elements.

Examples:

Input: S = “DDI”
Output: [3, 2, 0, 1]

Input: S = “IDID”
Output: [0, 4, 1, 3, 2]



Approach: If S[0] == “I”, then choose 0 as the first element. Similarly, if S[0] == “D”, then choose N as the first element. Now for every I operation, choose the next maximum element which hasn’t been chosen before from the range [0, N] and for the D operation, choose the next minimum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

//C++ Implementation of above approach 
#include<bits/stdc++.h>
using namespace std;
    // function to find minimum required permutation 
    void  StringMatch(string s) 
    {
    int lo=0, hi = s.length(), len=s.length(); 
    vector<int> ans;
    for (int x=0;x<len;x++)
    {
        if (s[x] == 'I'
        {
            ans.push_back(lo) ;
            lo += 1;
            }
        else
        {
            ans.push_back(hi) ;
            hi -= 1;
            }
    }
            ans.push_back(lo) ;
    cout<<"[";
    for(int i=0;i<ans.size();i++)
    {
    cout<<ans[i];
    if(i!=ans.size()-1)
    cout<<",";
    }
    cout<<"]";
}
// Driver code
int main()
{
string S = "IDID";
StringMatch(S); 
return 0;
}
//contributed by Arnab Kundu

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Implementation of above approach
  
# function to find minimum required permutation
def StringMatch(S):
    lo, hi = 0, len(S)
    ans = []
    for x in S:
        if x == 'I':
            ans.append(lo)
            lo += 1
        else:
            ans.append(hi)
            hi -= 1
  
    return ans + [lo]
  
# Driver code
S = "IDID"
print(StringMatch(S))

chevron_right


Output:

[0, 4, 1, 3, 2]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : andrew1234