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?- A. 3
- B. 1
- C. 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
- Problem: How many ordered sequences of 1s and 3s sum to 6? Run the code. python ways = [1] + [0] 6 for v in range(1, 7): for s in (1, 3)…
- Problem: What is the maximum XOR of any contiguous subarray of [8, 1, 2, 12]? Run the brute force. python a = [8, 1, 2, 12] best = 0 for i…
- Problem: Sort [1, 1, 2, 2, 2, 3] by frequency ascending, breaking ties by value ascending. What is printed? python from collections import…
- Problem: How many set bits are there in total across the numbers 0 to 7? Run the code. python print(sum(bin(i).count('1') for i in…
- Problem: How many integers in [1, 20] are powers of two? Run the code. python print(sum(1 for x in range(1, 21) if x & (x - 1) == 0)) What…
- Problem: How many integers in [1, 100] are divisible by 7 or by 11? Run the code. python print(sum(1 for x in range(1, 101) if x % 7 == 0…