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?- A. 10
- B. 6
- C. 15
- 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
- Problem: How many ways are there to place 2 non-attacking rooks on a 4 x 4 board? Run the code. python from itertools import combinations…
- Problem: How many integers in [1, 1000] have exactly three distinct decimal digits? Run the code. python print(sum(1 for x in range(1…
- Problem: How many primes p <= 200 have p + 6 also prime? Run the code. python def isp(n): return n > 1 and all(n % d for d in range(2…
- Problem: How many integers in [1, 2000] have an odd number of positive divisors? Run the code. python print(sum(1 for x in range(1, 2001)…
- Problem: How many 3-element subsets of {1, ..., 10} have sum 15? Run the code. python from itertools import combinations print(sum(1 for c…
- Problem: What is the largest k such that 2^k divides 12!? Run the code. python n = 12 c = 0 p = 2 while p <= n: c += n // p p = 2 print(c)…