Skip to content
Related Articles

Related Articles

Improve Article

Sum of the shortest distance between all 0s to 1 in given binary string

  • Last Updated : 24 Sep, 2021
Geek Week

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 to 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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the total sum of
// the shortest distance between every
// 0 to 1 in a given binary string
void findTotalDistance(string S, int N)
{
 
    // Stores the prefix distance and
    // suffix distance from 0 to 1
    vector<int> prefixDistance(N);
    vector<int> suffixDistance(N);
 
    // Stores the current distance
    // from 1 to 0
    int cnt = 0;
 
    // Marks the 1
    bool haveOne = false;
    for (int i = 0; i < N; ++i) {
 
        // If current character is 1
        if (S[i] == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign prefixDistance[i] as 0
            prefixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
            // Update prefixDistance[i]
            prefixDistance[i] = cnt;
        }
 
        // Assign prefixDistance[i]
        // as INT_MAX
        else
            prefixDistance[i] = INT_MAX;
    }
 
    // Assign haveOne as false
    haveOne = false;
    for (int i = N - 1; i >= 0; --i) {
 
        // If current character is 1
        if (S[i] == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign the suffixDistance[i]
            // as 0
            suffixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
 
            // Update suffixDistance[i]
            // as cnt
            suffixDistance[i] = cnt;
        }
        else
            // Assign suffixDistance[i]
            // as INT_MAX
            suffixDistance[i] = INT_MAX;
    }
 
    // Stores the total sum of distances
    // between 0 to nearest 1
    int sum = 0;
 
    for (int i = 0; i < N; ++i) {
 
        // If current character is 0
        if (S[i] == '0') {
 
            // Update the value of sum
            sum += min(prefixDistance[i],
                       suffixDistance[i]);
        }
    }
 
    // Print the value of the sum
    cout << sum << endl;
}
 
// Driver Code
int main()
{
    string S = "100100";
    int N = S.length();
 
    findTotalDistance(S, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
public class GFG{
 
// Function to find the total sum of
// the shortest distance between every
// 0 to 1 in a given binary string
static void findTotalDistance(String S, int N)
{
 
    // Stores the prefix distance and
    // suffix distance from 0 to 1
    int []prefixDistance = new int[N];
    int []suffixDistance = new int[N];
 
    // Stores the current distance
    // from 1 to 0
    int cnt = 0;
 
    // Marks the 1
    boolean haveOne = false;
    for (int i = 0; i < N; ++i) {
 
        // If current character is 1
        if (S.charAt(i) == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign prefixDistance[i] as 0
            prefixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
            // Update prefixDistance[i]
            prefixDistance[i] = cnt;
        }
 
        // Assign prefixDistance[i]
        // as INT_MAX
        else
            prefixDistance[i] = Integer.MAX_VALUE;
    }
 
    // Assign haveOne as false
    haveOne = false;
    for (int i = N - 1; i >= 0; --i) {
 
        // If current character is 1
        if (S.charAt(i) == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign the suffixDistance[i]
            // as 0
            suffixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
 
            // Update suffixDistance[i]
            // as cnt
            suffixDistance[i] = cnt;
        }
        else
            // Assign suffixDistance[i]
            // as INT_MAX
            suffixDistance[i] = Integer.MAX_VALUE;
    }
 
    // Stores the total sum of distances
    // between 0 to nearest 1
    int sum = 0;
 
    for (int i = 0; i < N; ++i) {
 
        // If current character is 0
        if (S.charAt(i) == '0') {
 
            // Update the value of sum
            sum += Math.min(prefixDistance[i],
                       suffixDistance[i]);
        }
    }
 
    // Print the value of the sum
    System.out.print(sum);
}
 
// Driver Code
public static void main(String []args)
{
    String S = "100100";
    int N = S.length();
 
    findTotalDistance(S, N);
}
}
 
// This code is contributed by AnkThon

Python3




# python program for the above approach
 
# Function to find the total sum of
# the shortest distance between every
# 0 to 1 in a given binary string
 
INT_MAX = 2147483647
 
 
def findTotalDistance(S, N):
 
    # Stores the prefix distance and
    # suffix distance from 0 to 1
    prefixDistance = [0 for _ in range(N)]
    suffixDistance = [0 for _ in range(N)]
 
    # Stores the current distance
    # from 1 to 0
    cnt = 0
 
    # Marks the 1
    haveOne = False
    for i in range(0, N):
 
        # If current character is 1
        if (S[i] == '1'):
 
            # // Mark haveOne to true
            haveOne = True
 
            # Assign the cnt to 0
            cnt = 0
 
            # Assign prefixDistance[i] as 0
            prefixDistance[i] = 0
 
        # If haveOne is true
        elif (haveOne):
 
            # Update the cnt
            cnt = cnt + 1
            # Update prefixDistance[i]
            prefixDistance[i] = cnt
 
        # Assign prefixDistance[i]
        # as INT_MAX
        else:
            prefixDistance[i] = INT_MAX
 
    # Assign haveOne as false
    haveOne = False
    for i in range(N-1, -1, -1):
 
        # If current character is 1
        if (S[i] == '1'):
 
            # Mark haveOne to true
            haveOne = True
 
            # Assign the cnt to 0
            cnt = 0
 
            # Assign the suffixDistance[i]
            # as 0
            suffixDistance[i] = 0
 
        # If haveOne is true
        elif (haveOne):
 
            # Update the cnt
            cnt = cnt + 1
 
            # Update suffixDistance[i]
            # as cnt
            suffixDistance[i] = cnt
 
        else:
            # // Assign suffixDistance[i]
            # // as INT_MAX
            suffixDistance[i] = INT_MAX
 
    # Stores the total sum of distances
    # between 0 to nearest 1
    sum = 0
 
    for i in range(0, N):
 
        # If current character is 0
        if (S[i] == '0'):
 
            # Update the value of sum
            sum += min(prefixDistance[i], suffixDistance[i])
 
    # Print the value of the sum
    print(sum)
 
 
# Driver Code
if __name__ == "__main__":
 
    S = "100100"
    N = len(S)
 
    findTotalDistance(S, N)
 
# This code is contributed by rakeshsahni

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the total sum of
// the shortest distance between every
// 0 to 1 in a given binary string
static void findTotalDistance(string S, int N)
{
 
    // Stores the prefix distance and
    // suffix distance from 0 to 1
    int []prefixDistance = new int[N];
    int []suffixDistance = new int[N];
 
    // Stores the current distance
    // from 1 to 0
    int cnt = 0;
 
    // Marks the 1
    bool haveOne = false;
    for (int i = 0; i < N; ++i) {
 
        // If current character is 1
        if (S[i] == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign prefixDistance[i] as 0
            prefixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
            // Update prefixDistance[i]
            prefixDistance[i] = cnt;
        }
 
        // Assign prefixDistance[i]
        // as INT_MAX
        else
            prefixDistance[i] = Int32.MaxValue;
    }
 
    // Assign haveOne as false
    haveOne = false;
    for (int i = N - 1; i >= 0; --i) {
 
        // If current character is 1
        if (S[i] == '1') {
 
            // Mark haveOne to true
            haveOne = true;
 
            // Assign the cnt to 0
            cnt = 0;
 
            // Assign the suffixDistance[i]
            // as 0
            suffixDistance[i] = 0;
        }
 
        // If haveOne is true
        else if (haveOne) {
 
            // Update the cnt
            cnt++;
 
            // Update suffixDistance[i]
            // as cnt
            suffixDistance[i] = cnt;
        }
        else
            // Assign suffixDistance[i]
            // as INT_MAX
            suffixDistance[i] = Int32.MaxValue;
    }
 
    // Stores the total sum of distances
    // between 0 to nearest 1
    int sum = 0;
 
    for (int i = 0; i < N; ++i) {
 
        // If current character is 0
        if (S[i] == '0') {
 
            // Update the value of sum
            sum += Math.Min(prefixDistance[i],
                       suffixDistance[i]);
        }
    }
 
    // Print the value of the sum
    Console.Write(sum);
}
 
// Driver Code
public static void Main()
{
    string S = "100100";
    int N = S.Length;
 
    findTotalDistance(S, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
    // JavaScript program for the above approach
    const INT_MAX = 2147483647
     
    // Function to find the total sum of
    // the shortest distance between every
    // 0 to 1 in a given binary string
    const findTotalDistance = (S, N) => {
 
        // Stores the prefix distance and
        // suffix distance from 0 to 1
        let prefixDistance = new Array(N).fill(0);
        let suffixDistance = new Array(N).fill(0);
 
        // Stores the current distance
        // from 1 to 0
        let cnt = 0;
 
        // Marks the 1
        let haveOne = false;
        for (let i = 0; i < N; ++i) {
 
            // If current character is 1
            if (S[i] == '1') {
 
                // Mark haveOne to true
                haveOne = true;
 
                // Assign the cnt to 0
                cnt = 0;
 
                // Assign prefixDistance[i] as 0
                prefixDistance[i] = 0;
            }
 
            // If haveOne is true
            else if (haveOne) {
 
                // Update the cnt
                cnt++;
                // Update prefixDistance[i]
                prefixDistance[i] = cnt;
            }
 
            // Assign prefixDistance[i]
            // as INT_MAX
            else
                prefixDistance[i] = INT_MAX;
        }
 
        // Assign haveOne as false
        haveOne = false;
        for (let i = N - 1; i >= 0; --i) {
 
            // If current character is 1
            if (S[i] == '1') {
 
                // Mark haveOne to true
                haveOne = true;
 
                // Assign the cnt to 0
                cnt = 0;
 
                // Assign the suffixDistance[i]
                // as 0
                suffixDistance[i] = 0;
            }
 
            // If haveOne is true
            else if (haveOne) {
 
                // Update the cnt
                cnt++;
 
                // Update suffixDistance[i]
                // as cnt
                suffixDistance[i] = cnt;
            }
            else
                // Assign suffixDistance[i]
                // as INT_MAX
                suffixDistance[i] = INT_MAX;
        }
 
        // Stores the total sum of distances
        // between 0 to nearest 1
        let sum = 0;
 
        for (let i = 0; i < N; ++i) {
 
            // If current character is 0
            if (S[i] == '0') {
 
                // Update the value of sum
                sum += Math.min(prefixDistance[i], suffixDistance[i]);
            }
        }
 
        // Print the value of the sum
        document.write(`${sum}<br/>`);
    }
 
    // Driver Code
 
    let S = "100100";
    let N = S.length;
 
    findTotalDistance(S, N);
 
// This code is contributed by rakeshsahni
 
</script>
Output: 
5

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :