Data Structures & AlgorithmsModerateTCS NQT · hashing warm-up

Problem: How many pairs of equal values (i < j, a[i] = a[j]) does a = [1, 2, 1, 3, 2, 2] contain? Run the code.

Problem: How many pairs of equal values (i < j, a[i] = a[j]) does a = [1, 2, 1, 3, 2, 2] contain? Run the code.
from collections import Counter
a = [1, 2, 1, 3, 2, 2]
print(sum(v * (v - 1) // 2 for v in Counter(a).values()))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: A. 4

The value 1 appears twice (1 pair) and 2 appears three times (3 pairs), giving 4. Counting ordered pairs would double the answer.

More Coding Interview Problems questions

Exams that ask this topic