- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- if s[right] is same as "1", then
- 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

- Related Questions & Answers
- Program to find length of longest repeating substring in a string in Python
- Program to find length of longest palindromic substring after single rotation in Python
- Program to find longest subarray of 1s after deleting one element using Python
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest substring with even vowel counts in Python
- Program to find length of longest consecutively increasing substring in Python
- Find length of longest subsequence of one string which is substring of another string in C++
- Program to find length of longest common substring in C++
- Find longest sequence of 1’s in binary representation with one flip in C++
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find length of longest substring with character count of at least k in Python
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to find length of longest alternating path of a binary tree in python

Advertisements