Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible.
Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible.
def min_remove(a, p):
need = sum(a) % p
if need == 0: return 0
last = {0: -1}; run = 0; best = len(a)
for i, x in enumerate(a):
run = (run + x) % p
want = (run - need) % p
if want in last:
best = min(best, i - last[want])
last[run] = i
return best if best < len(a) else -1
print(min_remove([5, 2, 7, 4], 5), min_remove([4, 8, 1, 6], 7), min_remove([2, 2], 5))What is printed?- A. 3 1 -1
- B. 1 2 -1
- C. 3 2 2
- D. 3 2 -1
Correct answer: D. 3 2 -1
We need a block with sum ≡ need = total mod p, i.e. prefix[j] − prefix[i] ≡ need, so look up the LATEST index of residue (prefix[j] − need) mod p. [5, 2, 7, 4]: total 18, need 3; no single element or pair is ≡ 3 (mod 5), but 2 + 7 + 4 = 13 is → 3. [4, 8, 1, 6]: total 19, need 5; 4 + 8 = 12 ≡ 5 (mod 7) → 2. [2, 2]: the only block is the whole array, which is forbidden → −1. O(n).
More Coding Interview Problems questions
- Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1. python…
- Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is…
- Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and…
- Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x…
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…
- Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings. python def…