Last Updated: 9 Sep, 2025

Optimal Character Rearrangement

Easy
Asked in company
PhonePe

Problem statement

You are given a string s. Your task is to rearrange the characters of s to create a new string, srearranged, such that the number of positions where s[i] != srearranged[i] is maximized.

You need to return this maximum possible number of mismatched positions.


Input Format:
The first line of input contains a single string s.


Output Format:
Print a single integer representing the maximum number of positions that can differ from the original string after rearrangement.


Note:
The key to this problem is identifying the character with the highest frequency. This "majority" character is the most constrained and limits our ability to create mismatches.
Let N be the length of the string and max_freq be the count of the most frequent character.
  1) If no single character is dominant (max_freq <= N / 2), we can always find a new position for every single character. In this case, the answer is N.
  2) If one character is dominant (max_freq > N / 2), some of these characters will inevitably have to be placed in positions originally held by the same character type. The number of unavoidable matches will be 2 * max_freq - N. The number of mismatches is N minus these unavoidable matches.