
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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 number of 1s after swapping one pair of bits in Python
- Program to find longest subarray of 1s after deleting one element using 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
- Program to find longest distance of 1s in binary form of a number using Python
- Find longest sequence of 1’s in binary representation with one flip in C++
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find length of longest substring with character count of at least k 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++
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to count substrings with all 1s in binary string in Python

Advertisements