VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-the-shortest-distance-between-all-0s-to-1-in-given-binary-string/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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:


Output: 
5

 

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

Comment