Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.)

Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.)
def can(a, k):
    s = sum(a)
    if s % k: return False
    t = s // k; a.sort(reverse=True)
    if a[0] > t: return False
    b = [0] * k
    def go(i):
        if i == len(a): return True
        seen = set()
        for j in range(k):
            if b[j] + a[i] <= t and b[j] not in seen:
                seen.add(b[j]); b[j] += a[i]
                if go(i + 1): return True
                b[j] -= a[i]
        return False
    return go(0)
print(can([2, 2, 2, 2, 3, 4, 5], 4), can([1, 2, 3, 4, 5, 6, 7, 8], 4))
What is printed?
  1. A. False True
  2. B. True True
  3. C. False False
  4. D. True False

Correct answer: A. False True

First case: the sum 20 gives target 5; 5 and 3 + 2 are fine, but 4 needs a 1, which does not exist, so False even though 20 is divisible by 4. Second: target 9 with {1,8}, {2,7}, {3,6}, {4,5}: True. Skipping buckets with an already-tried sum prunes symmetric branches.

More Coding Interview Problems questions

Exams that ask this topic