Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize characters to be removed from string with given condition
Next article icon

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

Last Updated : 17 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++




// C++ program to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find maximum number of removals
int maxRem(string str)
{
    // Map to store count of zeroes and ones
    map<char, int> mp;
    for (auto& value : str)
        mp[value]++;
 
    // If the count of both characters are same
    // then longest substring is the whole string
    // except the last character
    if (mp['0'] == mp['1']) {
        return (mp['0'] - 1);
    }
 
    // If the count of both characters
    // are unequal so the largest substring
    // is whole string and ans is
    // the minimum count of a character
    else
        return min(mp['0'], mp['1']);
}
 
// Driver code
int main()
{
    string str = "00110001000";
 
    int ans = maxRem(str);
    cout << ans;
    return 0;
}
 
 

Java




// Java program to implement the approach
import java.util.*;
class GFG{
 
  // Function to find maximum number of removals
  static int maxRem(String str)
  {
     
    // Map to store count of zeroes and ones
    HashMap<Character,Integer> mp = new HashMap<Character,Integer>();
    for (char value : str.toCharArray())
      if(mp.containsKey(value))
        mp.put(value, mp.get(value)+1);
    else
      mp.put(value, 1);
 
    // If the count of both characters are same
    // then longest subString is the whole String
    // except the last character
    if (mp.get('0') == mp.get('1')) {
      return (mp.get('0') - 1);
    }
 
    // If the count of both characters
    // are unequal so the largest subString
    // is whole String and ans is
    // the minimum count of a character
    else
      return Math.min(mp.get('0'), mp.get('1'));
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String str = "00110001000";
 
    int ans = maxRem(str);
    System.out.print(ans);
  }
}
 
// This code is contributed by shikhasingrajput
 
 

Python3




# Python program to implement the approach
# Function to find maximum number of removals
def maxRem(s, n):
 
    # Map to store count of zeroes and ones
    mp = {}
 
    for i in range(0, n):
        if(not mp.__contains__(s[i])):
            mp[s[i]] = 1
        else:
            mp[s[i]] += 1
 
    # If the count of both characters are same
    # then longest substring is the whole string
    # except the last character
    if(mp['0'] == mp['1']):
        return (mp['0'] - 1)
 
    # If the count of both characters
    # are unequal so the largest substring
    # is whole string and ans is
    # the minimum count of a character
    else:
        return min(mp['0'], mp['1'])
 
# Driver code
 
s = "00110001000"
n = len(s)
ans = maxRem(s, n)
print(ans)
 
# This code is contributed by Palak Gupta
 
 

C#




// C# program to implement the approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find maximum number of removals
  static int maxRem(string str)
  {
 
    // Map to store count of zeroes and ones
    Dictionary<char, int> mp =
      new Dictionary<char, int>();
 
    for (int i = 0; i < str.Length; i++) {
      if(!mp.ContainsKey(str[i])) {
        mp.Add(str[i], 1);
      }
      else {
        mp[str[i]] = mp[str[i]] + 1;
      }
    }
 
    // If the count of both characters are same
    // then longest substring is the whole string
    // except the last character
    if (mp['0'] == mp['1']) {
      return (mp['0'] - 1);
    }
 
    // If the count of both characters
    // are unequal so the largest substring
    // is whole string and ans is
    // the minimum count of a character
    else {
      return Math.Min(mp['0'], mp['1']);
    }
  }
 
  // Driver code
  public static void Main()
  {
    string str = "00110001000";
 
    int ans = maxRem(str);
    Console.Write(ans);
  }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find maximum number of removals
       function maxRem(str)
       {
        
           // Map to store count of zeroes and ones
           let mp = new Map();
           for (let i = 0; i < str.length; i++) {
               if (mp.has(str[i])) {
                   mp.set(str[i], mp.get(str[i]) + 1)
               }
               else {
                   mp.set(str[i], 1)
               }
           }
 
           // If the count of both characters are same
           // then longest substring is the whole string
           // except the last character
           if (mp.get('0') == mp.get('1')) {
               return (mp.get('0') - 1);
           }
 
           // If the count of both characters
           // are unequal so the largest substring
           // is whole string and ans is
           // the minimum count of a character
           else
               return Math.min(mp.get('0'), mp.get('1'));
       }
 
       // Driver code
       let str = "00110001000";
 
       let ans = maxRem(str);
       document.write(ans);
 
      // This code is contributed by Potta Lokesh
   </script>
 
 

 
 

Output
3

 

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

 



Next Article
Maximize characters to be removed from string with given condition
author
minatonamikaze55
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • binary-representation
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Maximize characters to be removed from string with given condition
    Given a string s. The task is to maximize the removal of characters from s. Any character can be removed if at least one of its adjacent characters is the previous letter in the Latin English alphabet. Examples: Input: s = "bacabcab"Output: 4Explanation: Following are the removals that maximize the
    6 min read
  • Maximum count of “010..” subsequences that can be removed from given Binary String
    Given a binary string S consisting of size N, the task is to find the maximum number of binary subsequences of the form "010.." of length at least 2 that can be removed from the given string S. Examples: Input: S = "110011010"Output: 3Explanation:Following are the subsequence removed:Operation 1: Ch
    6 min read
  • Maximize length of the String by concatenating characters from an Array of Strings
    Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
    12 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Count all palindromic Substrings for each character in a given String
    Given a string S of length n, for each character S[i], the task is to find the number of palindromic substrings of length K such that no substring should contain S[i], the task is to return an array A of length n, where A[i] is the count of palindromic substrings of length K which does not include t
    9 min read
  • Minimize String length by deleting Substring of same character when K flips are allowed
    Given a binary string consisting of '0' and '1' only and an integer K, the task is to minimize the string as far as possible by deleting a substring of the same character, when you can flip at most K characters. Examples: Input: S = "0110", K = 2Output: 0Explanation: We can make two '0' s into '1' o
    12 min read
  • Minimize a binary string by repeatedly removing even length substrings of same characters
    Given a binary string str of size N, the task is to minimize the length of given binary string by removing even length substrings consisting of sam characters, i.e. either 0s or 1s only, from the string any number of times. Finally, print the modified string. Examples: Input: str ="101001"Output: "1
    8 min read
  • Maximize partitions such that no two substrings have any common character
    Given string s of size n, the task is to print the number of substrings formed after maximum possible partitions such that no two substrings have a common character. Examples: Input : s = "ababcbacadefegdehijhklij" Output : 3 Explanation: Partitioning at the index 8 and at 15 produces three substrin
    1 min read
  • Maximize sum by splitting given binary strings based on given conditions
    Given two binary strings str1 and str2 each of length N, the task is to split the strings in such a way that the sum is maximum with given conditions. Split both strings at the same position into equal length substrings.If both the substrings have only 0's then the value of that substring to be adde
    7 min read
  • Longest Substring that can be made a palindrome by swapping of characters
    Given a numeric string S, the task is to find the longest non-empty substring that can be made palindrome. Examples: Input: S = "3242415"Output: 5Explanation: "24241" is the longest such substring which can be converted to the palindromic string "24142". Input: S = "213123"Output: 6Explanation: "213
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences