Data Structures & AlgorithmsModerateProduct Company SDE pattern

What is printed? (hash set for pairs with a given difference)

What is printed? (hash set for pairs with a given difference)
def pairs_diff(a, k):
    s = set(a)
    return sorted((x, x + k) for x in s if x + k in s)
print(pairs_diff([1, 7, 5, 9, 2, 12, 3], 2), len(pairs_diff([1, 1, 1, 2], 0)))
  1. A. [(1, 3), (3, 5), (5, 7), (7, 9)] 1
  2. B. [(1, 3), (5, 7), (7, 9)] 2
  3. C. [(1, 3), (3, 5), (5, 7), (7, 9), (10, 12)] 2
  4. D. [(1, 3), (3, 5), (5, 7), (7, 9)] 2

Correct answer: D. [(1, 3), (3, 5), (5, 7), (7, 9)] 2

With k = 2 the distinct pairs are (1,3), (3,5), (5,7), (7,9); 12 − 2 = 10 is absent. For k = 0 the set version is wrong: every distinct value pairs with itself, giving (1,1) and (2,2) = 2, although only 1 has a real duplicate (answer 1). k = 0 needs a count map (values seen at least twice). O(n).

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

Exams that ask this topic