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?- A. False True
- B. True True
- C. False False
- 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
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…
- A bitmask DP loops over every mask of n bits and, for each mask, over all of its submasks. What is the total number of (mask, submask)…
- Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element…
- Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious…
- Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix'). python def happy(s): p = [0] len(s); k = 0 for i…