Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together (e.g. "0011", "10").

Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together (e.g. "0011", "10").
def bin_sub(s):
    groups = []; cnt = 1
    for i in range(1, len(s)):
        if s[i] == s[i - 1]: cnt += 1
        else: groups.append(cnt); cnt = 1
    groups.append(cnt)
    return sum(min(a, b) for a, b in zip(groups, groups[1:]))
print(bin_sub("0001101"), bin_sub("1010"), bin_sub("111000"))
What is printed?
  1. A. 4 3 3
  2. B. 5 3 3
  3. C. 4 2 3
  4. D. 4 3 1

Correct answer: A. 4 3 3

Valid substrings straddle a boundary between two adjacent runs and use k characters from each side, k ≤ the smaller run. "0001101": runs 3, 2, 1, 1 → min(3,2) + min(2,1) + min(1,1) = 2 + 1 + 1 = 4 ("01", "0011", "10", "01"). "111000" → 3 ("10", "1100", "111000"). Counting all balanced substrings would include ones like "0110". O(n).

More Coding Interview Problems questions

Exams that ask this topic