Minimum operations require to balance Binary String
Last Updated :
06 Dec, 2023
Given a binary string S of length N, the task is to find the minimum number of operations required to balance (equal number of ‘0’ and ‘1’) the given binary string, you can perform two types of operations one at a time, which is given below.
- Remove a character from the front of the given string.
- Remove a character from the end of the given string.
Examples:
Input: S = “0111000”
Output: 1
Explanation: Remove 1 character from the front of the given string.
Input: S = “11100100”
Output: 0
If we assign value -1 to ‘0’ characters and the value of +1 to ‘1’ characters, then any valid substring in which the count of ‘0’s and ‘1’s are equal will result in zero sum. Now, the only task is to determine the length of the longest substring whose sum would be zero. The remaining character n – length of the longest substring with 0 sum would be the result.
Steps to solve this problem:
- Create a map unmap to store the prefix sums with their first occurrence indices.
- Iterate through the characters in the string s:
- For each character, update the prefixSum by +1 if the character is ‘1’, or -1 if the character is ‘0’.
- If the prefixSum becomes zero at any point, update result by (i + 1), this ensures that this is the longest valid substring encountered so far.
- Check if the current prefixSum value exists in the unmap.
- If true, update result again with the maximum of its current value and i – unmap[prefixSum], which calculates the length of the current valid substring.
- Otherwise, store current prefixSum in unmap with the index i.
- Finally, return the remaining length of the string, which is n – result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minOperation(string& s)
{
unordered_map< int , int > unmap;
int n = s.size();
int prefixSum = 0;
int result = 0;
for ( int i = 0; i < n; i++) {
prefixSum += ((s[i] == '1' ) ? 1 : -1);
if (prefixSum == 0) {
result = max(result, i + 1);
}
if (unmap.count(prefixSum)) {
result = max(result, i - unmap[prefixSum]);
}
else {
unmap[prefixSum] = i;
}
}
return n - result;
}
int main()
{
string S = "0111000" ;
int result = minOperation(S);
cout << result << endl;
return 0;
}
|
Java
import java.util.HashMap;
public class Main {
public static int minOperation(String s)
{
HashMap<Integer, Integer> unmap = new HashMap<>();
int n = s.length();
int prefixSum = 0 ;
int result = 0 ;
for ( int i = 0 ; i < n; i++) {
prefixSum += (s.charAt(i) == '1' ? 1 : - 1 );
if (prefixSum == 0 ) {
result = Math.max(result, i + 1 );
}
if (unmap.containsKey(prefixSum)) {
result = Math.max(result,
i - unmap.get(prefixSum));
}
else {
unmap.put(prefixSum, i);
}
}
return n - result;
}
public static void main(String[] args)
{
String S = "0111000" ;
int result = minOperation(S);
System.out.println(result);
}
}
|
Python3
def minOperation(s):
unmap = {}
n = len (s)
prefixSum = 0
result = 0
for i in range (n):
if s[i] = = '1' :
prefixSum + = 1
else :
prefixSum - = 1
if prefixSum = = 0 :
result = max (result, i + 1 )
if prefixSum in unmap:
result = max (result, i - unmap[prefixSum])
else :
unmap[prefixSum] = i
return n - result
if __name__ = = "__main__" :
S = "0111000"
result = minOperation(S)
print (result)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int MinOperation( string s)
{
Dictionary< int , int > unmap = new Dictionary< int , int >();
int n = s.Length;
int prefixSum = 0;
int result = 0;
for ( int i = 0; i < n; i++)
{
prefixSum += (s[i] == '1' ) ? 1 : -1;
if (prefixSum == 0)
{
result = Math.Max(result, i + 1);
}
if (unmap.ContainsKey(prefixSum))
{
result = Math.Max(result, i - unmap[prefixSum]);
}
else
{
unmap[prefixSum] = i;
}
}
return n - result;
}
static void Main()
{
string S = "0111000" ;
int result = MinOperation(S);
Console.WriteLine(result);
}
}
|
Javascript
function MinOperation(s) {
let unmap = new Map();
let n = s.length;
let prefixSum = 0;
let result = 0;
for (let i = 0; i < n; i++) {
prefixSum += (s[i] === '1' ) ? 1 : -1;
if (prefixSum === 0) {
result = Math.max(result, i + 1);
}
if (unmap.has(prefixSum)) {
result = Math.max(result, i - unmap.get(prefixSum));
} else {
unmap.set(prefixSum, i);
}
}
return n - result;
}
let S = "0111000" ;
let result = MinOperation(S);
console.log(result);
|
Time Complexity: O(N), where N is the length of the given binary string.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...