Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many subsets of {1, ..., 7} contain no two numbers that differ by exactly 1? Run the code.

Problem: How many subsets of {1, ..., 7} contain no two numbers that differ by exactly 1? Run the code.
print(sum(1 for m in range(1 << 7) if all(not ((m >> i) & 1 and (m >> (i + 1)) & 1) for i in range(6))))
What is printed?
  1. A. 33
  2. B. 34
  3. C. 21
  4. D. 55

Correct answer: B. 34

With a(n) = a(n−1) + a(n−2), a(1) = 2, a(2) = 3, the count for 7 is F(9) = 34, including the empty set. Leaving out the empty set gives 33, and 21 or 55 come from shifting the Fibonacci index.

More Coding Interview Problems questions

Exams that ask this topic