
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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.
Steps
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
Example
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]) j++; } return j; } int main() { string S = "acdb"; cout << solve(S) << endl; }
Input
"acdb"
Output
3
- Related Articles
- Check if characters of a given string can be rearranged to form a palindrome in Python
- Can part of a string be rearranged to form another string in JavaScript
- Find the count of sub-strings whose characters can be rearranged to form the given word in Python
- Check if a string can be rearranged to form special palindrome in Python
- Java program to check order of characters in string
- Program to count how many times we can find "pizza" with given string characters in Python
- Program to find squared elements list in sorted order in Python
- Program to find minimum required chances to form a string with K unique characters in Python
- Python Program to find mirror characters in a string
- Java Program to find duplicate characters in a String?
- Program to merge two sorted list to form larger sorted list in Python
- Check if characters of one string can be swapped to form other in Python
- Find the n-th binary string in sorted order in C++
- Java program to find all duplicate characters in a string
- Python program to find all duplicate characters in a string

Advertisements