Optimal Character Rearrangement

Easy
0/40
0 upvote
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.


Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1:
google


Sample Output 1:
6


Explanation for Sample 1:
The string is "google" (N=6). The character frequencies are g:2, o:2, l:1, e:1.
The highest frequency is 2. Since `2 <= 6 / 2`, no single character is dominant.
Therefore, we can rearrange the string so that every character moves to a new position.
Original:  g o o g l e
Rearranged: l e g g o o
All 6 positions are mismatched.


Sample Input 2:
banana


Sample Output 2:
6


Explanation for Sample 2:
The string is "banana" (N=6). Frequencies: a:3, n:2, b:1.
The highest frequency is 3 for 'a'. Since `3 <= 6 / 2`, 'a' is not a dominant majority.
We can rearrange all characters to achieve 6 mismatches. For example: `nanaba`.


Expected Time Complexity:
The expected time complexity is O(N), where N is the length of the string.


Constraints:
1 <= N <= 10^5
`s` consists of lowercase English letters.

Time limit: 1 sec
Approaches (1)
Optimal Character Rearrangement
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Optimal Character Rearrangement
Full screen
Console