Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s.
Examples:
Input: str = “00101101”
Output: 2
Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to “000111” or “001111” respectively. The number of removals required in both the cases is 2, which is the minimum possible.
Input: str = “111000001111”
Output: 3
Brute Force Approach:
- Initialize the minimum number of deletions required to be the length of the input string since we can delete all characters in the worst case to satisfy the condition.
- Iterate over each character i in the input string.
- Calculate the number of 1s before i and the number of 0s after i using the count() function in the STL.
- Calculate the total number of deletions required to make a substring of 0s followed by a substring of 1s using i as the midpoint.
- Update the minimum number of deletions required if the current substring requires fewer deletions.
- Return the minimum number of deletions required.
Below is the code of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumDeletions(string s)
{
int n = s.length();
int minDeletions = n;
for ( int i=0;i<n;i++)
{
int numOnesBefore = count(s.begin(), s.begin()+i, '1' );
int numZerosAfter = count(s.begin()+i, s.end(), '0' );
minDeletions = min(minDeletions, numOnesBefore + numZerosAfter);
}
return minDeletions;
}
int main()
{
string stri = "00101101" ;
cout << minimumDeletions(stri) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main
{
public static int minimumDeletions(String s) {
int n = s.length();
int minDeletions = n;
for ( int i= 0 ;i<n;i++) {
int numOnesBefore = count(s.substring( 0 , i), '1' );
int numZerosAfter = count(s.substring(i), '0' );
minDeletions = Math.min(minDeletions, numOnesBefore + numZerosAfter);
}
return minDeletions;
}
public static int count(String s, char c) {
int count = 0 ;
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String stri = "00101101" ;
System.out.println(minimumDeletions(stri));
}
}
|
Python
def minimum_deletions(s):
n = len (s)
min_deletions = n
for i in range (n):
num_ones_before = s[:i].count( '1' )
num_zeros_after = s[i:].count( '0' )
min_deletions = min (min_deletions, num_ones_before + num_zeros_after)
return min_deletions
if __name__ = = "__main__" :
stri = "00101101"
print (minimum_deletions(stri))
|
C#
using System;
class Program
{
static int MinimumDeletions( string s)
{
int n = s.Length;
int minDeletions = n;
for ( int i = 0; i < n; i++)
{
int numOnesBefore = CountOccurrences(s.Substring(0, i), '1' );
int numZerosAfter = CountOccurrences(s.Substring(i), '0' );
minDeletions = Math.Min(minDeletions, numOnesBefore + numZerosAfter);
}
return minDeletions;
}
static int CountOccurrences( string input, char target)
{
int count = 0;
foreach ( char c in input)
{
if (c == target)
count++;
}
return count;
}
static void Main()
{
string stri = "00101101" ;
Console.WriteLine(MinimumDeletions(stri));
}
}
|
Javascript
function minimumDeletions(s) {
const n = s.length;
let minDeletions = n;
for (let i = 0; i < n; i++) {
const numOnesBefore = s.substring(0, i).split( '1' ).length - 1;
const numZerosAfter = s.substring(i).split( '0' ).length - 1;
minDeletions = Math.min(minDeletions, numOnesBefore + numZerosAfter);
}
return minDeletions;
}
const stri = "00101101" ;
console.log(minimumDeletions(stri));
|
Time Complexity: O(N^2), where N is the length of the input string. The outer loop iterates over all possible positions in the string, and the count function inside the loop has a time complexity of O(N) for each call, giving an overall time complexity of O(N^2).
Auxiliary Space: O(1) because we are not using any additional data structures to store information about the input string.
Efficient Approach: The above approach can be optimized by having an auxiliary space that keeps the count of the number of 0s after 1s. Using this pre-computation, the time complexity can be improved by a factor of N. Below are the steps:
- Initialize a variable, say ans, to store the minimum number of characters required to be deleted.
- Initialize an array, say zeroCount[], to count the number of 0s present after a given index.
- Traverse the string str from the end over the range [N – 2, 0] and if the current character is 0, then update zeroCount[i] as (zeroCount[i + 1] + 1). Otherwise, update zeroCount[i] as zeroCount[i + 1].
- Initialize a variable, say oneCount, to count the number of 1s.
- Traverse the given string again. For every character found to be ‘1’, update ans as the minimum of ans and (oneCount + zeroCount[i]).
- After the above steps, if the value of ans remains same as its initialized value, then 0 characters are required to be deleted. Otherwise, ans is the required number of characters to be deleted.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int minimumDeletions(string s)
{
int n = s.size();
int zeroCount[n];
zeroCount[n - 1] = (s[n - 1] == '0' ) ? 1 : 0;
for ( int i = n - 2; i >= 0; i--)
zeroCount[i] = (s[i] == '0' ) ?
zeroCount[i + 1] + 1 :
zeroCount[i + 1];
int oneCount = 0;
int ans = INT_MAX;
for ( int i = 0; i < n; i++)
{
if (s[i] == '1' )
{
ans = min(ans,
oneCount +
zeroCount[i]);
oneCount++;
}
}
ans = min(ans, oneCount);
return (ans == INT_MAX) ? 0 : ans;
}
int main()
{
string stri = "00101101" ;
cout << minimumDeletions(stri) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int minimumDeletions(String s)
{
int n = s.length();
int zeroCount[] = new int [n];
zeroCount[n - 1 ] = (s.charAt(n - 1 )
== '0' )
? 1
: 0 ;
for ( int i = n - 2 ; i >= 0 ; i--)
zeroCount[i] = (s.charAt(i) == '0' )
? zeroCount[i + 1 ] + 1
: zeroCount[i + 1 ];
int oneCount = 0 ;
int ans = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++) {
if (s.charAt(i) == '1' ) {
ans = Math.min(ans,
oneCount
+ zeroCount[i]);
oneCount++;
}
}
ans = Math.min(ans, oneCount);
return (ans == Integer.MAX_VALUE)
? 0
: ans;
}
public static void main(String[] args)
{
String str = "00101101" ;
System.out.println(
minimumDeletions(str));
}
}
|
Python3
def minimumDeletions(s):
n = len (s)
zeroCount = [ 0 for i in range (n)]
zeroCount[n - 1 ] = 1 if s[n - 1 ] = = '0' else 0
for i in range (n - 2 , - 1 , - 1 ):
zeroCount[i] = zeroCount[i + 1 ] + 1 if (s[i] = = '0' ) else zeroCount[i + 1 ]
oneCount = 0
ans = 10 * * 9
for i in range (n):
if (s[i] = = '1' ):
ans = min (ans,oneCount + zeroCount[i])
oneCount + = 1
ans = min (ans, oneCount)
return 0 if ans = = 10 * * 18 else ans
if __name__ = = '__main__' :
str = "00101101"
print (minimumDeletions( str ))
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static int minimumDeletions(String s)
{
int n = s.Length;
int []zeroCount = new int [n];
zeroCount[n - 1] = (s[n - 1]
== '0' )
? 1
: 0;
for ( int i = n - 2; i >= 0; i--)
zeroCount[i] = (s[i] == '0' )
? zeroCount[i + 1] + 1
: zeroCount[i + 1];
int oneCount = 0;
int ans = int .MaxValue;
for ( int i = 0; i < n; i++) {
if (s[i] == '1' ) {
ans = Math.Min(ans,
oneCount
+ zeroCount[i]);
oneCount++;
}
}
ans = Math.Min(ans, oneCount);
return (ans == int .MaxValue)
? 0
: ans;
}
public static void Main(String[] args)
{
String str = "00101101" ;
Console.WriteLine(
minimumDeletions(str));
}
}
|
Javascript
<script>
function minimumDeletions(s)
{
let n = s.length;
let zeroCount = [];
zeroCount[n - 1] = (s[n - 1]
== '0' )
? 1
: 0;
for (let i = n - 2; i >= 0; i--)
zeroCount[i] = (s[i] == '0' )
? zeroCount[i + 1] + 1
: zeroCount[i + 1];
let oneCount = 0;
let ans = Number.MAX_VALUE;
for (let i = 0; i < n; i++) {
if (s[i] == '1' ) {
ans = Math.min(ans,
oneCount
+ zeroCount[i]);
oneCount++;
}
}
ans = Math.min(ans, oneCount);
return (ans == Number.MAX_VALUE)
? 0
: ans;
}
let str = "00101101" ;
document.write(
minimumDeletions(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
11 Oct, 2023
Like Article
Save Article