2723. Find the Longest Balanced Substring of a Binary String
My accepted Python solution to LeetCode problem 2723, Find the Longest Balanced Substring of a Binary String, running in 0ms.
- Difficulty: Easy
- Python
- Runtime 0ms
- Memory 17.3MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 0ms, memory 17.3MB, accepted 2026-01-01.
class Solution:
def findTheLongestBalancedSubstring(self, s: str) -> int:
max_len = 0
zeros = 0
ones = 0
for c in s:
if c == '0':
if ones > 0: # Reset when we see 0 after seeing 1
zeros = 0
ones = 0
zeros += 1
else: # c == '1'
ones += 1
# Update max length: balanced means min(zeros, ones) pairs
max_len = max(max_len, 2 * min(zeros, ones))
return max_len