Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA

Binary string s = "1101001110001011". Find the length of the longest contiguous substring that contains equally many 0s and 1s.

Binary string s = "1101001110001011". Find the length of the longest contiguous substring that contains equally many 0s and 1s.
s="1101001110001011"
f={0:-1}; b=0; best=0
for i,ch in enumerate(s):
    b+=1 if ch=='1' else -1
    if b in f: best=max(best,i-f[b])
    else: f[b]=i
print(best)
What is printed?
  1. A. 14
  2. B. 6
  3. C. 3
  4. D. 13

Correct answer: A. 14

Map each running balance (ones minus zeros) to its first index; a repeated balance closes a substring with equal counts. Overwriting with the latest index shortens the answer, treating a zero as a zero step breaks the balance, and an off-by-one in the length drops a character.

More Coding Interview Problems questions

Exams that ask this topic