ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode (duplicate detection using a set)?

What will be the output of the following pseudocode (duplicate detection using a set)?
Function hasDuplicate(Array arr)
    Set seen = empty set
    for (each x in arr)
        if (x in seen)
            return true
        end if
        add(seen, x)
    end for
    return false
End Function

Print hasDuplicate({1, 2, 3, 4, 2}), hasDuplicate({1, 2, 3})
  1. A. true false
  2. B. false true
  3. C. false false
  4. D. true true

Correct answer: A. true false

The first array has 2 appearing twice, so the function finds it already in seen on the second pass and returns true. The second array has no repeats, so it returns false after scanning fully.

More Pseudocode and Code Tracing questions

Exams that ask this topic