Data Structures & AlgorithmsModerateFlipkart/Uber OA · placement

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 = [8, 7, 7, 10, 5, 11, 7, 6, 12, 9], 2
s = set(a)
print(sum(1 for x in s if x + k in s), len(s))
  1. A. 5 8
  2. B. 8 8
  3. C. 6 10
  4. D. 6 8

Correct answer: D. 6 8

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

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

Exams that ask this topic