ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode (counting distinct pairs whose difference is k)? (Arrays are indexed from 0.)

What will be the output of the following pseudocode (counting distinct pairs whose difference is k)? (Arrays are indexed from 0.)
Integer arr[5] = {1, 5, 3, 4, 2}
Integer k = 2
Set arrSet = toSet(arr)
Set pairs = empty set
for (each x in arr)
    if (x + k in arrSet)
        add(pairs, (min(x, x+k), max(x, x+k)))
    end if
end for
Print size(pairs)
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

The pairs with a difference of 2 are (1,3), (2,4), (3,5); using a set of sorted pairs avoids counting each pair twice, giving 3 distinct pairs.

More Pseudocode and Code Tracing questions

Exams that ask this topic