VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-minority-character-deletions-that-can-be-done-from-given-binary-string-substring/

⇱ Maximize minority character deletions that can be done from given Binary String substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize minority character deletions that can be done from given Binary String substring

Last Updated : 17 Mar, 2022

Python

Given binary string str of size, N. Select any substring from the string and remove all the occurrences of the minority character (i.e. the character having less frequency) from the substring. The task is to find out the maximum number of characters that can be removed from performing one such operation.

Note: If any substring has both '0' and '1' in the same numbers then no character can be removed.

Examples:

Input: str = "01"
Output: 0
Explanation: No character can be removed.
The substrings are "0", "1" and "01".
For "0" minority character is '1' and removing that from this substring is not possible as no '1' here.
Same for the substring "1". And substring "01" has no minority element.
The occurrences of both '1' and '0' are same in "01" substring.

Input: str = "00110001000"
Output: 3
Explanation: Remove all 1s from the substring "1100010".

Approach: Following are the cases for maximum possible deletions

  • Case-1: When all the 0s or 1s can be removed. When the total count of '0' and '1' are not same select the entire string and remove all the occurrences of the minority element.
  • Case-2: When both the characters are in same number. Here choosing the entire string will not be able to remove any character. So take a substring in such a way that the count of one of the character is same as of its count in actual string and for the other it is one less. So then possible removals are (count of any character in whole string - 1).
  • Case-3: When the string contains only one type of character. Then no removal is possible.

Below is the implementation of the above approach.

 
 


Output
3


 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment
Article Tags: