Minimum count of 0s to be removed from given Binary string to make all 1s occurs consecutively
Last Updated :
11 Sep, 2022
Given a binary string S of size N, the task is to find the minimum numbers of 0s that must be removed from the string S such that all the 1s occurs consecutively.
Examples:
Input: S = "010001011"
Output: 4
Explanation:
Removing the characters { S[2], S[3], S[4], S[6] } from the string S modifies the string S to "01111".
Therefore, the required output is 4.
Input: S = "011110000"
Output: 0
Explanation:
All 1s in S already group together, therefore, the required output is 0.
Approach: The given problem can be solved by observing the fact that removing leading and ending 0s in the string doesn't minimizes the count of 0s that must be removed. Therefore, the idea is to find the first and the last occurrence of 1 in the string S and find the count of 0s between them. Follow the steps below to solve the problem:
- Iterate over the characters of the string, S from left to right and find the index of first occurrence of 1s in the given string say X.
- Traverse the string from right to left and find the index of last occurrence of 1s in the given string say Y.
- After completing the above steps, print the count of 0s between the index X and Y as the result.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum count of
// 0s removed from the string S such
// that all 1s occurs consecutively
void makeContiguous(string S, int N)
{
// Stores the first and the last
// occurrence of 1
int fst_occur, lst_occur;
// Iterate over the characters
// the string, S
for (int x = 0; x < N; x++) {
// If current character
// is '1'
if (S[x] == '1') {
// Update fst_occur
fst_occur = x;
break;
}
}
// Iterate over the characters
// the string, S
for (int x = N - 1; x >= 0; x--) {
// If current character
// is '1'
if (S[x] == '1') {
// Update lst_occur
lst_occur = x;
break;
}
}
// Stores the count of 0s between
// fst_occur and lst_occur
int count = 0;
// Iterate over the characters of S
// between fst_occur and lst_occur
for (int x = fst_occur;
x <= lst_occur; x++) {
// If current character is '0'
if (S[x] == '0') {
// Update count
count++;
}
}
// Print the resultant minimum count
cout << count;
}
// Driver Code
int main()
{
string S = "010001011";
int N = S.size();
makeContiguous(S, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find minimum count of
// 0s removed from the String S such
// that all 1s occurs consecutively
static void makeContiguous(String S, int N)
{
// Stores the first and the last
// occurrence of 1
int fst_occur=0, lst_occur=0;
// Iterate over the characters
// the String, S
for (int x = 0; x < N; x++) {
// If current character
// is '1'
if (S.charAt(x) == '1') {
// Update fst_occur
fst_occur = x;
break;
}
}
// Iterate over the characters
// the String, S
for (int x = N - 1; x >= 0; x--) {
// If current character
// is '1'
if (S.charAt(x) == '1') {
// Update lst_occur
lst_occur = x;
break;
}
}
// Stores the count of 0s between
// fst_occur and lst_occur
int count = 0;
// Iterate over the characters of S
// between fst_occur and lst_occur
for (int x = fst_occur; x <= lst_occur; x++) {
// If current character is '0'
if (S.charAt(x) == '0') {
// Update count
count++;
}
}
// Print the resultant minimum count
System.out.print(count);
}
// Driver Code
public static void main(String[] args)
{
String S = "010001011";
int N = S.length();
makeContiguous(S, N);
}
}
// This code is contributed by gauravrajput1
Python3
# Python3 program for the above approach
# Function to find minimum count of
# 0s removed from the string S such
# that all 1s occurs consecutively
def makeContiguous(S, N):
# Stores the first and the last
# occurrence of 1
fst_occur = 0
lst_occur = 0
# Iterate over the characters
# the string, S
for x in range(N):
# If current character
# is '1'
if (S[x] == '1'):
# Update fst_occur
fst_occur = x
break
# Iterate over the characters
# the string, S
x = N - 1
while(x >= 0):
# If current character
# is '1'
if (S[x] == '1'):
# Update lst_occur
lst_occur = x
break
x -= 1
# Stores the count of 0s between
# fst_occur and lst_occur
count = 0
# Iterate over the characters of S
# between fst_occur and lst_occur
for x in range(fst_occur,lst_occur+1,1):
# If current character is '0'
if (S[x] == '0'):
# Update count
count += 1
# Print the resultant minimum count
print(count)
# Driver Code
if __name__ == '__main__':
S = "010001011"
N = len(S)
makeContiguous(S, N)
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
class GFG{
// Function to find minimum count of
// 0s removed from the string S such
// that all 1s occurs consecutively
static void makeContiguous(string S, int N)
{
// Stores the first and the last
// occurrence of 1
int fst_occur = 0, lst_occur = 0;
// Iterate over the characters
// the string, S
for(int x = 0; x < N; x++)
{
// If current character
// is '1'
if (S[x] == '1')
{
// Update fst_occur
fst_occur = x;
break;
}
}
// Iterate over the characters
// the string, S
for(int x = N - 1; x >= 0; x--)
{
// If current character
// is '1'
if (S[x] == '1')
{
// Update lst_occur
lst_occur = x;
break;
}
}
// Stores the count of 0s between
// fst_occur and lst_occur
int count = 0;
// Iterate over the characters of S
// between fst_occur and lst_occur
for(int x = fst_occur; x <= lst_occur; x++)
{
// If current character is '0'
if (S[x] == '0')
{
// Update count
count++;
}
}
// Print the resultant minimum count
Console.Write(count);
}
// Driver Code
public static void Main()
{
string S = "010001011";
int N = S.Length;
makeContiguous(S, N);
}
}
// This code is contributed by sanjoy_62
JavaScript
<script>
// javascript program for the above approach
// Function to find minimum count of
// 0s removed from the String S such
// that all 1s occurs consecutively
function makeContiguous( S , N)
{
// Stores the first and the last
// occurrence of 1
var fst_occur = 0, lst_occur = 0;
// Iterate over the characters
// the String, S
for (var x = 0; x < N; x++) {
// If current character
// is '1'
if (S.charAt(x) == '1') {
// Update fst_occur
fst_occur = x;
break;
}
}
// Iterate over the characters
// the String, S
for (var x = N - 1; x >= 0; x--) {
// If current character
// is '1'
if (S.charAt(x) == '1') {
// Update lst_occur
lst_occur = x;
break;
}
}
// Stores the count of 0s between
// fst_occur and lst_occur
var count = 0;
// Iterate over the characters of S
// between fst_occur and lst_occur
for (x = fst_occur; x <= lst_occur; x++) {
// If current character is '0'
if (S.charAt(x) == '0') {
// Update count
count++;
}
}
// Print the resultant minimum count
document.write(count);
}
// Driver Code
var S = "010001011";
var N = S.length;
makeContiguous(S, N);
// This code is contributed by umadevi9616
</script>
Time complexity: O(N) where N is the length of the given binary string
Auxiliary space: O(1), as constant extra space is required
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
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read