Data Structures & AlgorithmsHardTCS NQT · sets

Problem: How many integers in [1, 100] are perfect squares or perfect cubes? Run the code.

Problem: How many integers in [1, 100] are perfect squares or perfect cubes? Run the code.
sq = {x * x for x in range(1, 11)}
cu = {x ** 3 for x in range(1, 5)}
print(len(sq | cu))
What is printed?
  1. A. 14
  2. B. 10
  3. C. 12
  4. D. 16

Correct answer: C. 12

There are 10 squares (1 to 100) and 4 cubes (1, 8, 27, 64). The value 1 and 64 are in both sets, so the union has 10 + 4 - 2 = 12 elements.

More Coding Interview Problems questions

Exams that ask this topic