Program to find length of longest substring with 1s in a binary string after one 0-flip in Python

PythonServer Side ProgrammingProgramming

Suppose we have a binary string s. We are allowed to flip at most one "0" to "1", we have to find the length of the longest contiguous substring of 1s.

So, if the input is like s = "1010110001", then the output will be 4, as if we flip the zero present at index 3, then we get the string "1011110001", here length of the longest substring of 1s is 4.

To solve this, we will follow these steps −

  • n := size of s
  • ans := 0, ones := 0, left := 0, right := 0
  • while right < n, do
    • if s[right] is same as "1", then
      • ones := ones + 1
    • while right - left + 1 - ones > 1, do
      • remove := s[left]
      • if remove is same as "1", then
        • ones := ones - 1
      • left := left + 1
    • ans := maximum of ans and (right - left + 1)
    • right := right + 1
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(s):
   n = len(s)
   ans = ones = left = right = 0
   while right < n:
      if s[right] == "1":
         ones += 1
      while right - left + 1 - ones > 1:
         remove = s[left]
         if remove == "1":
            ones -= 1
         left += 1
      ans = max(ans, right - left + 1)
      right += 1
   return ans

s = "1010110001"
print(solve(s))

Input

"1010110001"

Output

4
raja
Updated on 19-Oct-2021 10:24:25

Advertisements