26.Number following a pattern

Given a pattern containing only I's and D's. I for increasing and D for decreasing. Devise an algorithm to print the minimum number following that pattern. Digits from 1-9 and digits can't repeat.

Example 1:

Input:
D
Output:
21
Explanation:
D is meant for decreasing,
So we choose the minimum number
among 21,31,54,87,etc.

Example 2:

Input:
IIDDD
Output:
126543
Explanation:
Above example is self- explanatory,
1 < 2 < 6 > 5 > 4 > 3
  I - I - D - D - D

Solution: (Stack)

Approach: Pop when there is I Add in rest cases

// Some code
class solution
{
public:
    string printMinNumberForPattern(string s)
    {
        // code here
        stack<int> st;
        string res = "";
        for (int i = 0; i <= s.length(); i++)
        {
            st.push(i + 1);

            if (i == s.length() || s[i] == 'I')
            {

                while (!st.empty())
                {
                    int k = st.top();
                    st.pop();
                    res += to_string(k);
                }
            }
        }

        return res;
    }
};

Last updated