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 longest number of 1s after swapping one pair of bits in Python
Suppose we have a binary string s. If we can swap at most one pair of characters in the string, we have to find the resulting length of the longest contiguous substring of 1s.
So, if the input is like s = "1111011111", then the output will be 9, as we can swap s[4] and s[9] to get 9 consecutive 1s.
Algorithm
To solve this, we will follow these steps −
- l := 0, cnt := 0, ans := 0
- for r in range 0 to size of s, do
- cnt := cnt + (1 when s[r] is same as "0" otherwise 0)
- if cnt > 1, then
- cnt := cnt - (1 when s[l] is same as "0" otherwise 0)
- l := l + 1
- ans := maximum of ans and (r - l + 1)
- return minimum of ans and occurrence of 1 in s
Implementation
Let us see the following implementation to get better understanding −
class Solution:
def solve(self, s):
l = 0
cnt = 0
ans = 0
for r in range(len(s)):
cnt += s[r] == "0"
if cnt > 1:
cnt -= s[l] == "0"
l += 1
ans = max(ans, r - l + 1)
return min(ans, s.count("1"))
ob = Solution()
s = "1111011111"
print(ob.solve(s))
The output of the above code is −
9
How It Works
The algorithm uses a sliding window approach with two pointers:
- l (left pointer): Left boundary of the current window
- r (right pointer): Right boundary expanding through the string
- cnt: Count of zeros in the current window
The window maintains at most one zero. When we encounter a second zero, we shrink the window from the left until we have at most one zero again. This ensures we can always swap that single zero with a one from outside the window.
Example Walkthrough
For s = "1111011111":
s = "1111011111"
solution = Solution()
# Step by step visualization
for i, char in enumerate(s):
print(f"Index {i}: '{char}'")
result = solution.solve(s)
print(f"\nLongest sequence after swap: {result}")
Index 0: '1' Index 1: '1' Index 2: '1' Index 3: '1' Index 4: '0' Index 5: '1' Index 6: '1' Index 7: '1' Index 8: '1' Index 9: '1' Longest sequence after swap: 9
Key Points
- The algorithm allows at most one zero in the sliding window
- We return
min(ans, s.count("1"))because we can't have more 1s than originally present - Time complexity: O(n), Space complexity: O(1)
Conclusion
This sliding window approach efficiently finds the longest possible sequence of 1s after swapping one pair of bits. The key insight is maintaining at most one zero in the current window, representing the bit we can swap.
