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?- A. 14
- B. 6
- C. 3
- 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
- Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and…
- Coins of denominations 1, 3 and 4 are available with unlimited supply. For the amount 6, run the DP that finds the minimum number of coins…
- Array a = [1, 3, 2, 3, 1, 4, 5, 2]. Subsequences are chosen by index (positions may repeat values). Count the strictly increasing…
- Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost…
- A staircase is climbed with steps of size 1, 3 or 4 (order of steps matters). How many distinct ordered sequences of steps reach exactly…
- Forty-one people stand in a circle numbered 1 to 41. Starting from person 1, every third person is removed, repeatedly, counting continues…