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?
  1. A. 3 1 -1
  2. B. 1 2 -1
  3. C. 3 2 2
  4. 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

Exams that ask this topic