Count of substrings with equal ratios of 0s and 1s till ith index in given Binary String
Last Updated :
23 Nov, 2021
Given a binary string S, the task is to print the maximum number of substrings with equal ratios of 0s and 1s till the ith index from the start.
Examples:
Input: S = "110001"
Output: {1, 2, 1, 1, 1, 2}
Explanation: The given string can be partitioned into the following equal substrings:
- Valid substrings upto index 0 : "1", possible no. of substrings = 1
- Valid substrings upto index 1 : "1", "B", possible no. of substrings = 2
- Valid substrings upto index 2 : "110", possible no. of substrings = 1
- Valid substrings upto index 3 : "1100", possible no. of substrings = 1
- Valid substrings upto index 4 : "11000", possible no. of substrings = 1
- Valid substrings upto index 5 : "1100", "01", possible no. of substrings = 2
Input: S = "010100001"
Output: {1, 1, 1, 2, 1, 2, 1, 1, 3}
Approach: The task can be solved using mathematical concepts & HashMap to store the frequencies of pairs Follow the below steps to solve the problem:
- Create two prefix arrays for occurrences of 0s and 1s say pre0[] and pre1[] respectively.
- For each prefix, label it with a pair (a, b) where a = frequency of ‘0’ and b = frequency of ‘1’ in this prefix. Divide a and b by gcd(a, b) to get the simplest form.
- Iterate over all prefixes, and store the answer for the prefix as the current number of occurrences of this pair.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to retuan a prefix array of
// equal partitions of the given string
// consisting of 0s and 1s
void equalSubstrings(string s)
{
// Length of the string
int n = s.size();
// Prefix arrays for 0s and 1s
int pre0[n] = { 0 }, pre1[n] = { 0 };
// If character at index 0 is 0
if (s[0] == '0') {
pre0[0] = 1;
}
// If character at index 0 is 1
else {
pre1[0] = 1;
}
// Filling the prefix arrays
for (int i = 1; i < n; i++) {
if (s[i] == '0') {
pre0[i] = pre0[i - 1] + 1;
pre1[i] = pre1[i - 1];
}
else {
pre0[i] = pre0[i - 1];
pre1[i] = pre1[i - 1] + 1;
}
}
// Vector to store the answer
vector<int> ans;
// Map to store the ratio
map<pair<int, int>, int> mp;
for (int i = 0; i < n; i++) {
// Find the gcd of pre0[i] and pre1[i]
int x = __gcd(pre0[i], pre1[i]);
// Converting the elements in
// simplest form
int l = pre0[i] / x, r = pre1[i] / x;
// Update the value in map
mp[{ l, r }]++;
// Store this in ans
ans.push_back(mp[{ l, r }]);
}
// Return the ans vector
for (auto i : ans)
cout << i << " ";
}
// Driver Code
int main()
{
string s = "001110";
equalSubstrings(s);
return 0;
}
Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
class GFG
{
// Function to retuan a prefix array of
// equal partitions of the given string
// consisting of 0s and 1s
public static void equalSubstrings(String s)
{
// Length of the string
int n = s.length();
// Prefix arrays for 0s and 1s
int[] pre0 = new int[n];
int[] pre1 = new int[n];
Arrays.fill(pre0, 0);
Arrays.fill(pre1, 0);
// If character at index 0 is 0
if (s.charAt(0) == '0') {
pre0[0] = 1;
}
// If character at index 0 is 1
else {
pre1[0] = 1;
}
// Filling the prefix arrays
for (int i = 1; i < n; i++) {
if (s.charAt(i) == '0') {
pre0[i] = pre0[i - 1] + 1;
pre1[i] = pre1[i - 1];
} else {
pre0[i] = pre0[i - 1];
pre1[i] = pre1[i - 1] + 1;
}
}
// Vector to store the answer
ArrayList<Integer> ans = new ArrayList<Integer>();
// Map to store the ratio
HashMap<String, Integer> mp = new HashMap<String, Integer>();
for (int i = 0; i < n; i++)
{
// Find the gcd of pre0[i] and pre1[i]
int x = __gcd(pre0[i], pre1[i]);
// Converting the elements in
// simplest form
int l = pre0[i] / x, r = pre1[i] / x;
String key = l + "," + r;
// Update the value in map
if (mp.containsKey(key))
mp.put(key, mp.get(key) + 1);
else
mp.put(key, 1);
// Store this in ans
ans.add(mp.get(key));
}
// Return the ans vector
for (int i : ans)
System.out.print(i + " ");
}
public static int __gcd(int a, int b) {
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Driver Code
public static void main(String args[]) {
String s = "001110";
equalSubstrings(s);
}
}
// This code is contributed by gfgking.
Python3
# Python program for the above approach
def __gcd(a, b):
if (b == 0):
return a
return __gcd(b, a % b)
# Function to retuan a prefix array of
# equal partitions of the given string
# consisting of 0s and 1s
def equalSubstrings(s):
# Length of the string
n = len(s)
# Prefix arrays for 0s and 1s
pre0 = [0] * n
pre1 = [0] * n
# If character at index 0 is 0
if (s[0] == '0'):
pre0[0] = 1
# If character at index 0 is 1
else:
pre1[0] = 1
# Filling the prefix arrays
for i in range(1, n):
if (s[i] == '0'):
pre0[i] = pre0[i - 1] + 1
pre1[i] = pre1[i - 1]
else:
pre0[i] = pre0[i - 1]
pre1[i] = pre1[i - 1] + 1
# Vector to store the answer
ans = []
# Map to store the ratio
mp = {}
for i in range(n):
# Find the gcd of pre0[i] and pre1[i]
x = __gcd(pre0[i], pre1[i])
# Converting the elements in
# simplest form
l = pre0[i] // x
r = pre1[i] // x
# Update the value in map
if (f'[{l}, {r}]' in mp):
mp[f'[{l}, {r}]'] += 1
else:
mp[f'[{l}, {r}]'] = 1
# Store this in ans
ans.append(mp[f'[{l}, {r}]'])
# Return the ans vector
for i in ans:
print(i, end=" ")
# Driver Code
s = "001110"
equalSubstrings(s)
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to retuan a prefix array of
// equal partitions of the given string
// consisting of 0s and 1s
public static void equalSubstrings(string s)
{
// Length of the string
int n = s.Length;
// Prefix arrays for 0s and 1s
int[] pre0 = new int[n];
int[] pre1 = new int[n];
// Arrays.fill(pre0, 0);
// Arrays.fill(pre1, 0);
// If character at index 0 is 0
if (s[0] == '0') {
pre0[0] = 1;
}
// If character at index 0 is 1
else {
pre1[0] = 1;
}
// Filling the prefix arrays
for (int i = 1; i < n; i++) {
if (s[i] == '0') {
pre0[i] = pre0[i - 1] + 1;
pre1[i] = pre1[i - 1];
}
else {
pre0[i] = pre0[i - 1];
pre1[i] = pre1[i - 1] + 1;
}
}
// Vector to store the answer
List<int> ans = new List<int>();
// Map to store the ratio
Dictionary<string, int> mp
= new Dictionary<string, int>();
for (int i = 0; i < n; i++) {
// Find the gcd of pre0[i] and pre1[i]
int x = __gcd(pre0[i], pre1[i]);
// Converting the elements in
// simplest form
int l = pre0[i] / x, r = pre1[i] / x;
string key = l + "," + r;
// Update the value in map
if (mp.ContainsKey(key))
mp[key] += 1;
else
mp[key] = 1;
// Store this in ans
ans.Add(mp[key]);
}
// Return the ans vector
foreach(int i in ans) Console.Write(i + " ");
}
public static int __gcd(int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Driver Code
public static void Main(string[] args)
{
string s = "001110";
equalSubstrings(s);
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// JavaScript program for the above approach
const __gcd = (a, b) => {
if (b == 0) return a;
return __gcd(b, a % b)
}
// Function to retuan a prefix array of
// equal partitions of the given string
// consisting of 0s and 1s
const equalSubstrings = (s) => {
// Length of the string
let n = s.length;
// Prefix arrays for 0s and 1s
let pre0 = new Array(n).fill(0);
let pre1 = new Array(n).fill(0);
// If character at index 0 is 0
if (s[0] == '0') {
pre0[0] = 1;
}
// If character at index 0 is 1
else {
pre1[0] = 1;
}
// Filling the prefix arrays
for (let i = 1; i < n; i++) {
if (s[i] == '0') {
pre0[i] = pre0[i - 1] + 1;
pre1[i] = pre1[i - 1];
}
else {
pre0[i] = pre0[i - 1];
pre1[i] = pre1[i - 1] + 1;
}
}
// Vector to store the answer
ans = [];
// Map to store the ratio
mp = {};
for (let i = 0; i < n; i++) {
// Find the gcd of pre0[i] and pre1[i]
let x = __gcd(pre0[i], pre1[i]);
// Converting the elements in
// simplest form
let l = pre0[i] / x, r = pre1[i] / x;
// Update the value in map
if ([l, r] in mp) mp[[l, r]] += 1
else mp[[l, r]] = 1
// Store this in ans
ans.push(mp[[l, r]]);
}
// Return the ans vector
for (let i in ans)
document.write(`${ans[i]} `);
}
// Driver Code
let s = "001110";
equalSubstrings(s);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
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
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
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
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