Longest Substring with Equal Number of 0s and 1s

viaLeetCode

Problem: Given a binary string, find the length of the longest contiguous substring that contains an equal number of 0s and 1s.

Constraints: String length up to 10^5.

Example: "11010011" -> longest balanced substring is length 8 ("11010011" itself), or e.g. "0011" for a shorter example.

Approach: Convert each '0' to -1 and each '1' to +1, compute prefix sums. Two indices i<j give a balanced substring (i, j] iff prefix[i] == prefix[j]. Track the earliest index for each prefix-sum value seen (hashmap) and, for every later index with the same running sum, compute the length; keep the max. O(n) time, O(n) space.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account