Orderly Queue in C++

C++Server Side ProgrammingProgramming

Suppose there is a string S. All letters in S are in lowercase. Then, we may make any number of moves.

Here, in each move, we choose one of the first K letters, and remove it, and place it at the end of the string. We have to find the lexicographically smallest string we could have after any number of moves.

So, if the input is like "cabaa" and K = 3, then the output will be "aaabc"

To solve this, we will follow these steps −

  • if K > 1, then −

    • sort the array S

    • return S

  • ret := S

  • n := size of S

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

    • S := cut the first character of S and add it at the end into S

    • if S < ret, then −

      • ret = S

  • return ret

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   string orderlyQueue(string S, int K) {
      if(K > 1){
         sort(S.begin(), S.end());
         return S;
      string ret = S;
      int n = S.size();
      for(int i = 1; i < n; i++){
         S = S.substr(1) + S.substr(0, 1);
         if(S < ret) ret = S;
      return ret;
   Solution ob;
   cout << (ob.orderlyQueue("cabaa", 3));


"cabaa", 3


Published on 04-Jun-2020 12:24:37