Data Structures & AlgorithmsHardICPC regional · bitmask counting
Problem: How many subsets (including the empty one) of {1, 2, 3, 4, 5} have a sum divisible by 4? Run the code.
Problem: How many subsets (including the empty one) of {1, 2, 3, 4, 5} have a sum divisible by 4? Run the code.
print(sum(1 for m in range(1 << 5) if sum(i + 1 for i in range(5) if m >> i & 1) % 4 == 0))What is printed?
- A. 7
- B. 24
- C. 5
- D. 8
Correct answer: D. 8
Subset sums divisible by 4 are 0 (empty set), 4, 8 and 12, giving 8 subsets. Excluding the empty set gives 7, counting the non-divisible sums gives 24, and checking only sums 4 and 8 misses the empty set and the sum-12 subsets {3, 4, 5} and {1, 2, 4, 5}, giving 5.
More Coding Interview Problems questions
- Problem: What does the following print? It takes the maximum of every window of size 2 in [4, 2, 12, 11, -5]. python a = [4, 2, 12, 11…
- Problem: What is the sum of the number of 1-bits in the binary representations of 1, 2, ..., 20? Run the code. python…
- Problem: Which statement about shortest paths in a weighted directed acyclic graph (DAG) is correct?
- Problem: Which statement about Floyd-Warshall on a graph with V = 400 vertices and no negative cycles is correct?
- Problem: Minimum number of taps needed to water a garden of length 5 is found from tap i covering [i - ri, i + ri]. Here n = 5 and r = [3…
- Problem: A stone game: piles [5, 3, 4, 5] lie in a row, and players alternately take a pile from either end. The first player wants to…