Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many distinct sums of two different elements of [1, 2, 4, 8] are there? Run the code.

Problem: How many distinct sums of two different elements of [1, 2, 4, 8] are there? Run the code.
from itertools import combinations
print(len({x + y for x, y in combinations([1, 2, 4, 8], 2)}))
What is printed?
  1. A. 10
  2. B. 6
  3. C. 15
  4. D. 12

Correct answer: B. 6

Sums of two different powers of two are all distinct, so C(4,2) = 6. Letting an element pair with itself gives 10, 15 counts all non-empty subset sums, and 12 counts ordered pairs.

More Coding Interview Problems questions

Exams that ask this topic