Length of the longest substring with equal 1s and 0s
Last Updated :
22 Feb, 2023
Given a binary string. We need to find the length of the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1.
Examples:
Input : input = 110101010
Output : Length of longest balanced sub string = 8
Input : input = 0000
Output : Length of longest balanced sub string = 0
A simple solution is to use two nested loops to generate every substring. And a third loop to count number of 0s and 1s in current substring.
Below is the implementation of the above approach:
C++
// C++ program to find the length of
// the longest balanced substring
#include <bits/stdc++.h>
using namespace std;
// Function to check if a string contains
// equal number of one and zeros or not
bool isValid(string p)
{
int n = p.length();
int c1 = 0, c0 = 0;
for (int i = 0; i < n; i++) {
if (p[i] == '0')
c0++;
if (p[i] == '1')
c1++;
}
return (c0 == c1) ? true : false;
}
// Function to find the length of
// the longest balanced substring
int longestSub(string s)
{
int max_len = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (isValid(s.substr(i, j - i + 1)) && max_len < j - i + 1)
max_len = j - i + 1;
}
}
return max_len;
}
// Driver code
int main()
{
string s = "101001000";
// Function call
cout << longestSub(s);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to find the length of
// the longest balanced substring
import java.io.*;
import java.util.*;
class GFG
{
// Function to check if a string contains
// equal number of one and zeros or not
public static boolean isValid(String p)
{
int n = p.length();
int c1 = 0, c0 = 0;
for (int i = 0; i < n; i++)
{
if(p.charAt(i) == '0')
{
c0++;
}
if(p.charAt(i) == '1')
{
c1++;
}
}
if(c0 == c1)
{
return true;
}
else
{
return false;
}
}
// Function to find the length of
// the longest balanced substring
public static int longestSub(String s)
{
int max_len = 0;
int n = s.length();
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++)
{
if(isValid(s.substring(i, j + 1)) && max_len < j - i + 1)
{
max_len = j - i + 1;
}
}
}
return max_len;
}
// Driver code
public static void main (String[] args)
{
String s = "101001000";
// Function call
System.out.println(longestSub(s));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 program to find the length of
# the longest balanced substring
# Function to check if a contains
# equal number of one and zeros or not
def isValid(p):
n = len(p)
c1 = 0
c0 = 0
for i in range(n):
if (p[i] == '0'):
c0 += 1
if (p[i] == '1'):
c1 += 1
if (c0 == c1):
return True
else:
return False
# Function to find the length of
# the longest balanced substring
def longestSub(s):
max_len = 0
n = len(s)
for i in range(n):
for j in range(i, n):
if (isValid(s[i : j - i + 1]) and
max_len < j - i + 1):
max_len = j - i + 1
return max_len
# Driver code
if __name__ == '__main__':
s = "101001000"
# Function call
print(longestSub(s))
# This code is contributed by mohit kumar 29
C#
// C# program to find the length of
// the longest balanced substring
using System;
class GFG{
// Function to check if a string contains
// equal number of one and zeros or not
static bool isValid(string p)
{
int n = p.Length;
int c1 = 0, c0 = 0;
for(int i = 0; i < n; i++)
{
if (p[i] == '0')
{
c0++;
}
if (p[i] == '1')
{
c1++;
}
}
if (c0 == c1)
{
return true;
}
else
{
return false;
}
}
// Function to find the length of
// the longest balanced substring
public static int longestSub(string s)
{
int max_len = 0;
int n = s.Length;
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++)
{
if (isValid(s.Substring(i, j - i + 1)) &&
max_len < j - i + 1)
{
max_len = j - i + 1;
}
}
}
return max_len;
}
// Driver code
static public void Main()
{
string s = "101001000";
// Function call
Console.WriteLine(longestSub(s));
}
}
// This code is contributed by rag2127
JavaScript
<script>
// Javascript program to find the length of
// the longest balanced substring
// Function to check if a string contains
// equal number of one and zeros or not
function isValid(p)
{
var n = p.length;
var c1 = 0, c0 = 0;
for(var i =0; i < n; i++)
{
if(p[i] == '0')
c0++;
if(p[i] == '1')
c1++;
}
return (c0 == c1) ? true : false;
}
// Function to find the length of
// the longest balanced substring
function longestSub(s)
{
var max_len = 0;
var n = s.length;
for(var i = 0; i < n; i++)
{
for(var j = i; j < n; j++)
{
if(isValid(s.substr(i, j - i + 1)) && max_len < j - i + 1)
max_len = j - i + 1;
}
}
return max_len;
}
// Driver code
var s = "101001000";
// Function call
document.write( longestSub(s));
</script>
Time Complexity: O(N3)
Auxiliary Space: O(1)
An efficient solution is to use hashing.
- Traverse string and keep track of counts of 1s and 0s as count_1 and count_0 respectively.
- See if current difference between two counts has appeared before (We use hashing to store all differences and first index where a difference appears). If yes, then substring from previous appearance and current index has same number of 0s and 1s.
Below is the implementation of above approach.
C++
// C++ for finding length of longest balanced
// substring
#include<bits/stdc++.h>
using namespace std;
// Returns length of the longest substring
// with equal number of zeros and ones.
int stringLen(string str)
{
// Create a map to store differences
// between counts of 1s and 0s.
map<int, int> m;
// Initially difference is 0.
m[0] = -1;
int count_0 = 0, count_1 = 0;
int res = 0;
for (int i=0; i<str.size(); i++)
{
// Keeping track of counts of
// 0s and 1s.
if (str[i] == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (m.find(count_1 - count_0) != m.end())
res = max(res, i - m[count_1 - count_0]);
// If current difference is seen first time.
else
m[count_1 - count_0] = i;
}
return res;
}
// driver function
int main()
{
string str = "101001000";
cout << "Length of longest balanced"
" sub string = ";
cout << stringLen(str);
return 0;
}
Java
// Java Code for finding the length of
// the longest balanced substring
import java.io.*;
import java.util.*;
public class MAX_LEN_0_1 {
public static void main(String args[])throws IOException
{
String str = "101001000";
// Create a map to store differences
//between counts of 1s and 0s.
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
// Initially difference is 0;
map. put(0, -1);
int res =0;
int count_0 = 0, count_1 = 0;
for(int i=0; i<str.length();i++)
{
// Keep track of count of 0s and 1s
if(str.charAt(i)=='0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if(map.containsKey(count_1-count_0))
res = Math.max(res, (i - map.get(count_1-count_0)));
// If the current difference is seen first time.
else
map.put(count_1-count_0,i);
}
System.out.println("Length of longest balanced sub string = "+res);
}
}
Python3
# Python3 code for finding length of
# longest balanced substring
# Returns length of the longest substring
# with equal number of zeros and ones.
def stringLen( str ):
# Create a python dictionary to store
# differences between counts of 1s and 0s.
m = dict()
# Initially difference is 0.
m[0] = -1
count_0 = 0
count_1 = 0
res = 0
for i in range(len(str)):
# Keeping track of counts of
# 0s and 1s.
if str[i] == '0':
count_0 += 1
else:
count_1 += 1
# If difference between current
# counts already exists, then
# substring between previous and
# current index has same no. of
# 0s and 1s. Update result if
# this substring is more than
# current result.
if m.get(count_1 - count_0)!=None:
res = max(res, i - m[count_1 - count_0])
# If current difference is
# seen first time.
else:
m[count_1 - count_0] = i
return res
# driver code
str = "101001000"
print("Length of longest balanced"
" sub string = ",stringLen(str))
# This code is contributed by "Sharad_Bhardwaj"
C#
// C# Code for finding the length of
// the longest balanced substring
using System;
using System.Collections.Generic;
class GFG
{
public static void Main(string[] args)
{
string str = "101001000";
// Create a map to store differences
//between counts of 1s and 0s.
Dictionary<int,
int> map = new Dictionary<int,
int>();
// Initially difference is 0;
map[0] = -1;
int res = 0;
int count_0 = 0, count_1 = 0;
for (int i = 0; i < str.Length;i++)
{
// Keep track of count of 0s and 1s
if (str[i] == '0')
{
count_0++;
}
else
{
count_1++;
}
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (map.ContainsKey(count_1 - count_0))
{
res = Math.Max(res, (i - map[count_1 -
count_0]));
}
// If the current difference is
// seen first time.
else
{
map[count_1 - count_0] = i;
}
}
Console.WriteLine("Length of longest balanced" +
" sub string = " + res);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript Code for finding the length of
// the longest balanced substring
let str = "101001000";
// Create a map to store differences
// between counts of 1s and 0s.
let map = new Map();
// Initially difference is 0;
map.set(0, -1);
let res =0;
let count_0 = 0, count_1 = 0;
for(let i=0; i<str.length;i++)
{
// Keep track of count of 0s and 1s
if(str[i]=='0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if(map.has(count_1-count_0))
res =
Math.max(res, (i -
map.get(count_1-count_0)));
// If the current difference
// is seen first time.
else
map.set(count_1-count_0,i);
}
document.write(
"Length of longest balanced sub string = "+res
);
// This code is contributed by unknown2108
</script>
OutputLength of longest balanced sub string = 6
Time Complexity: O(n)
Auxiliary Space: O(n)
Extended Problem: Largest subarray with equal number of 0s and 1s
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read