Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Algorithm
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
# Test the function
s = "1010110001"
print(f"Input: {s}")
print(f"Output: {solve(s)}")
Input: 1010110001 Output: 4
How It Works
The algorithm uses a sliding window approach with two pointers:
- ones tracks the count of 1s in the current window
- right - left + 1 - ones gives the count of 0s in the window
- We maintain at most one 0 in the window (allowing one flip)
- When zeros exceed 1, we shrink the window from the left
Additional Example
Let's test with another binary string ?
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
# Test with different strings
test_cases = ["111000", "000111", "101010", "1111"]
for s in test_cases:
result = solve(s)
print(f"String: {s} ? Longest substring: {result}")
String: 111000 ? Longest substring: 4 String: 000111 ? Longest substring: 4 String: 101010 ? Longest substring: 3 String: 1111 ? Longest substring: 4
Conclusion
This sliding window technique efficiently finds the longest substring of 1s after flipping at most one 0. The algorithm runs in O(n) time complexity with O(1) space complexity.
