Data Structures & AlgorithmsModerateTCS NQT · subset sums
Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code.
Problem: How many subsets of [1, 2, 3, 4, 5] have a sum of exactly 7? Run the code.
from itertools import combinations a = [1, 2, 3, 4, 5] print(sum(1 for r in range(len(a) + 1) for c in combinations(a, r) if sum(c) == 7))What is printed?
- A. 2
- B. 4
- C. 5
- D. 3
Correct answer: D. 3
The subsets are {2,5}, {3,4} and {1,2,4}. Missing the three-element subset is the common error here.
More Coding Interview Problems questions
- Problem: What is the length of the longest arithmetic subsequence of [1, 3, 5, 7, 4]? Run the O(n^2) DP code. python a = [1, 3, 5, 7, 4] n…
- Problem: What is the minimum path sum from the top to the bottom of the triangle [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]], moving to an…
- Problem: How many unordered pairs (i < j) of 1..10 have a sum divisible by 5? Run the code. python a = list(range(1, 11)) print(sum(1 for…
- Problem: Minimum number of operations to reduce x = 5 to 0 by removing a number from either end of [1, 1, 4, 2, 3] (each removal subtracts…
- Problem: How many ordered sequences of 1s and 3s sum to 6? Run the code. python ways = [1] + [0] 6 for v in range(1, 7): for s in (1, 3)…
- Problem: What is the maximum XOR of any contiguous subarray of [8, 1, 2, 12]? Run the brute force. python a = [8, 1, 2, 12] best = 0 for i…