Sum of the shortest distance between all 0s to 1 in given binary string
Given a binary string S, the task is to find the sum of the shortest distance between all 0s to 1 in the given string S.
Examples:
Input: S = “100100”
Output: 5
Explanation:
For the ‘0’ at index 1 the nearest ‘1’ is at index 0 at a distance 1.
For the ‘0’ at index 2 the nearest ‘1’ is at index 3 at a distance 1.
For the ‘0’ at index 4 the nearest ‘1’ is at index 3 at a distance 1.
For the ‘0’ at index 5 the nearest ‘1’ is at index 3 at a distance 2.
Therefore the sum of the distances is 1 + 1 + 1 + 2 = 5.
Input: S = “1111”
Output: 0
Approach: The given problem can be solved by using the Greedy Approach. The idea is to search for the ‘1′ for each ‘0′ which is nearest to it from the left side. Similarly, search for the ‘1′ for each ‘0’ which is nearest to it from the right side. Finally, calculate the sum of the distances which is minimum for any ‘0′ to ‘1′ from the calculated value of right and left sides. Follow the below steps to solve the given problem.
- Initialize the two arrays prefixDistance(N), suffixDistance(N) to store distance from left and right respectively.
- Initialize a variable, say cnt = 0 that store the distance between any ‘0′ to nearest ‘1′.
- Initialize a variable, say haveOne = false, to mark the character ‘1′.
- Initialize a variable, say sum = 0 that stores the total sum between all the ‘0′ to its nearest ‘1′.
- Iterate over the range [0, N – 1] using the variable i perform the following steps:
- If the value of S[i] is ‘1′ then assign haveOne as true, cnt as 0 and prefixDistance[i] as 0.
- Otherwise, if haveOne is true then increment the value of cnt by 1 and assign the value of prefixDistance[i] as cnt.
- Iterate over the range [0, N – 1] using the variable i perform the following steps:
- If the value of S[i] is ‘1′ then assign haveOne as true, cnt as 0 and suffixDistance[i] as 0.
- Otherwise, if haveOne is true then increment the value of cnt by 1 and assign the value of suffixDistance[i] as cnt.
- Iterate over the range [0, N – 1] using the variable i and if the value of S[i] is ‘1′ then update the sum as sum += min(prefixDistance[i], suffixDistance[i]).
- After completing the above steps, print the value of the sum as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findTotalDistance(string S, int N)
{
vector< int > prefixDistance(N);
vector< int > suffixDistance(N);
int cnt = 0;
bool haveOne = false ;
for ( int i = 0; i < N; ++i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
prefixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
prefixDistance[i] = cnt;
}
else
prefixDistance[i] = INT_MAX;
}
haveOne = false ;
for ( int i = N - 1; i >= 0; --i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
suffixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
suffixDistance[i] = cnt;
}
else
suffixDistance[i] = INT_MAX;
}
int sum = 0;
for ( int i = 0; i < N; ++i) {
if (S[i] == '0' ) {
sum += min(prefixDistance[i],
suffixDistance[i]);
}
}
cout << sum << endl;
}
int main()
{
string S = "100100" ;
int N = S.length();
findTotalDistance(S, N);
return 0;
}
|
Java
import java.io.*;
public class GFG{
static void findTotalDistance(String S, int N)
{
int []prefixDistance = new int [N];
int []suffixDistance = new int [N];
int cnt = 0 ;
boolean haveOne = false ;
for ( int i = 0 ; i < N; ++i) {
if (S.charAt(i) == '1' ) {
haveOne = true ;
cnt = 0 ;
prefixDistance[i] = 0 ;
}
else if (haveOne) {
cnt++;
prefixDistance[i] = cnt;
}
else
prefixDistance[i] = Integer.MAX_VALUE;
}
haveOne = false ;
for ( int i = N - 1 ; i >= 0 ; --i) {
if (S.charAt(i) == '1' ) {
haveOne = true ;
cnt = 0 ;
suffixDistance[i] = 0 ;
}
else if (haveOne) {
cnt++;
suffixDistance[i] = cnt;
}
else
suffixDistance[i] = Integer.MAX_VALUE;
}
int sum = 0 ;
for ( int i = 0 ; i < N; ++i) {
if (S.charAt(i) == '0' ) {
sum += Math.min(prefixDistance[i],
suffixDistance[i]);
}
}
System.out.print(sum);
}
public static void main(String []args)
{
String S = "100100" ;
int N = S.length();
findTotalDistance(S, N);
}
}
|
Python3
INT_MAX = 2147483647
def findTotalDistance(S, N):
prefixDistance = [ 0 for _ in range (N)]
suffixDistance = [ 0 for _ in range (N)]
cnt = 0
haveOne = False
for i in range ( 0 , N):
if (S[i] = = '1' ):
haveOne = True
cnt = 0
prefixDistance[i] = 0
elif (haveOne):
cnt = cnt + 1
prefixDistance[i] = cnt
else :
prefixDistance[i] = INT_MAX
haveOne = False
for i in range (N - 1 , - 1 , - 1 ):
if (S[i] = = '1' ):
haveOne = True
cnt = 0
suffixDistance[i] = 0
elif (haveOne):
cnt = cnt + 1
suffixDistance[i] = cnt
else :
suffixDistance[i] = INT_MAX
sum = 0
for i in range ( 0 , N):
if (S[i] = = '0' ):
sum + = min (prefixDistance[i], suffixDistance[i])
print ( sum )
if __name__ = = "__main__" :
S = "100100"
N = len (S)
findTotalDistance(S, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void findTotalDistance( string S, int N)
{
int []prefixDistance = new int [N];
int []suffixDistance = new int [N];
int cnt = 0;
bool haveOne = false ;
for ( int i = 0; i < N; ++i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
prefixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
prefixDistance[i] = cnt;
}
else
prefixDistance[i] = Int32.MaxValue;
}
haveOne = false ;
for ( int i = N - 1; i >= 0; --i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
suffixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
suffixDistance[i] = cnt;
}
else
suffixDistance[i] = Int32.MaxValue;
}
int sum = 0;
for ( int i = 0; i < N; ++i) {
if (S[i] == '0' ) {
sum += Math.Min(prefixDistance[i],
suffixDistance[i]);
}
}
Console.Write(sum);
}
public static void Main()
{
string S = "100100" ;
int N = S.Length;
findTotalDistance(S, N);
}
}
|
Javascript
<script>
const INT_MAX = 2147483647
const findTotalDistance = (S, N) => {
let prefixDistance = new Array(N).fill(0);
let suffixDistance = new Array(N).fill(0);
let cnt = 0;
let haveOne = false ;
for (let i = 0; i < N; ++i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
prefixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
prefixDistance[i] = cnt;
}
else
prefixDistance[i] = INT_MAX;
}
haveOne = false ;
for (let i = N - 1; i >= 0; --i) {
if (S[i] == '1' ) {
haveOne = true ;
cnt = 0;
suffixDistance[i] = 0;
}
else if (haveOne) {
cnt++;
suffixDistance[i] = cnt;
}
else
suffixDistance[i] = INT_MAX;
}
let sum = 0;
for (let i = 0; i < N; ++i) {
if (S[i] == '0' ) {
sum += Math.min(prefixDistance[i], suffixDistance[i]);
}
}
document.write(`${sum}<br/>`);
}
let S = "100100" ;
let N = S.length;
findTotalDistance(S, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
01 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...