Data Structures & AlgorithmsModerateTCS Digital · Infosys SP

Count pairs with a given difference k (k > 0) among DISTINCT values using a hash set. What is printed?

Count pairs with a given difference k (k > 0) among DISTINCT values using a hash set. What is printed?
a, k = [2, 11, 6, 2, 5, 9, 8, 12, 9, 5], 3
s = set(a)
print(sum(1 for x in s if x + k in s), len(s))
  1. A. 4 7
  2. B. 5 8
  3. C. 5 7
  4. D. 8 7

Correct answer: C. 5 7

Iterating over the SET counts each distinct pair (x, x + k) once; iterating over the list counts duplicates repeatedly. Output: 5 7.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic