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?- A. 4 3 3
- B. 5 3 3
- C. 4 2 3
- 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
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…
- Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros…
- Problem: Minimum single-bit flips in a and b so that (a OR b) == c. python def minflips(a, b, c): flips = 0 while a or b or c: x, y, z = a…
- Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by…
- Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word. python…