Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Can an array be split into two subsets with equal sums?
Problem: Can an array be split into two subsets with equal sums?
def can_split(a):
s = sum(a)
if s % 2: return False
reach = 1
for x in a:
reach |= reach << x
return bool(reach >> (s // 2) & 1)
print(can_split([1, 5, 11, 5]), can_split([1, 2, 3, 5]), can_split([3, 3, 3, 4, 5]))What is printed?- A. True False False
- B. True False True
- C. True True True
- D. False False True
Correct answer: B. True False True
Subset-sum to half the total. The integer 'reach' is a bitset: bit k is set if sum k is achievable; shifting by x adds x to every reachable sum. [1, 5, 11, 5] → 11 = 11 = 1 + 5 + 5. [1, 2, 3, 5] has an odd total 11. [3, 3, 3, 4, 5] → 9 = 4 + 5 = 3 + 3 + 3. O(n · S / wordsize) with a bitset, O(n·S) with a boolean table.
More Coding Interview Problems questions
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…
- Problem: Find the largest square of 1s in a binary matrix and return its area. python def square(m): R, C = len(m), len(m[0]); dp = [[0]…
- Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit. python def cooldown(p): hold…
- Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number. python from functools import…