Find Permutation in C++

C++Server Side ProgrammingProgramming

Suppose we have a secret signature consisting of character 'D' and 'I'. 'D' denotes the decreasing relationship between two numbers, 'I' denotes increasing relationship between two numbers. And the secret signature was constructed by a special integer array, which contains uniquely all the different number from 1 to n.

For example, the secret signature "DI" can be constructed from an array like [2,1,3] or [3,1,2], but not be constructed using array like [3,2,4] or [2,1,3,4], which are both illegal constructing special string that can't represent the "DI" secret signature.

Now we have to find the lexicographically smallest permutation of [1, 2, ... n] that could refer to the given secret signature in the input.

So, if the input is like "DI", then the output will be [2,1,3], As we know [3,1,2] can also construct the secret signature "DI", but since we want to find the one with the smallest lexicographical permutation, we need to output [2,1,3]

To solve this, we will follow these steps −

  • Define one stack st

  • cnt := 2

  • Define an array ret

  • for initialize i := 1, when i <= size of s, update (increase i by 1), do −

    • if s[i - 1] is same as 'D', then −

      • insert i into st

    • Otherwise

      • insert i at the end of ret

      • while (not st is empty), do −

        • insert top element of st at the end of ret

        • delete element from st

  • insert size of s into st

  • while (not st is empty), do −

    • insert top element of st at the end of ret

    • delete element from st

  • return ret


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   cout << "]"<<endl;
class Solution {
   vector<int< findPermutation(string s) {
      stack <int< st;
      int cnt = 2;
      vector <int< ret;
      for(int i = 1; i <= s.size(); i++){
         if(s[i - 1] == 'D'){
      st.push(s.size() + 1);
      return ret;
   Solution ob;




[2, 1, 3, 5, 4, ]
Published on 19-Nov-2020 09:58:08