C++ program to find how many characters should be rearranged to order string in sorted form

Suppose we have a string S with n characters. S contains lowercase letters only. We must select a number k in range 0 to n, then select k characters from S and permute them in any order. In this process, the remaining characters will remain unchanged. We perform this whole operation exactly once. We have to find the value of k, for which S becomes sorted in alphabetical order.

So, if the input is like S = "acdb", then the output will be 3, because 'a' is at the correct place and remaining characters should be rearranged.


To solve this, we will follow these steps −

n := size of S
d := S
sort the array d
j := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   if S[i] is not equal to d[i], then:
      (increase j by 1)
return j


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

int solve(string S) {
   int n = S.size();
   string d = S;
   sort(d.begin(), d.end());
   int j = 0;
   for (int i = 0; i < n; i++) {
      if (S[i] != d[i])
   return j;

int main() {
   string S = "acdb";
   cout << solve(S) << endl;