Data Structures & AlgorithmsHardProduct Company SDE · two pointers OA

Problem: Minimum number of operations to reduce x = 5 to 0 by removing a number from either end of [1, 1, 4, 2, 3] (each removal subtracts the removed value from x). Run the brute-force code.

Problem: Minimum number of operations to reduce x = 5 to 0 by removing a number from either end of [1, 1, 4, 2, 3] (each removal subtracts the removed value from x). Run the brute-force code.
from itertools import product
a = [1, 1, 4, 2, 3]
n = len(a)
best = None
for k in range(n + 1):
    for left in range(k + 1):
        right = k - left
        if left + right <= n and sum(a[:left]) + sum(a[n - right:] if right else []) == 5:
            best = k if best is None else min(best, k)
print(best)
What is printed?
  1. A. 3
  2. B. 1
  3. C. 4
  4. D. 2

Correct answer: D. 2

Removing 2 and 3 from the two ends sums to 5 in two operations, and no single removal equals 5. The brute force checks every split of prefix and suffix lengths.

More Coding Interview Problems questions

Exams that ask this topic