

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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 find minimum required chances to form a string with K unique characters in Python
- Program to find squared elements list in sorted order in Python
- Program to count how many times we can find "pizza" with given string characters in Python
- Program to count how many numbers should be appended to create all numbers from 1 to k in C++
- Program to find out how many transfer requests can be satisfied in Python
- Check if characters of one string can be swapped to form other in Python
- Python - Find indices where elements should be inserted to maintain order in Pandas Index
- Program to merge two sorted list to form larger sorted list in Python
- Java Program to find duplicate characters in a String?
- Python Program to find mirror characters in a string
Advertisements