ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer a[7] = {10, 5, 3, 4, 3, 5, 6}
Set seen = empty
Integer first = -1
for (each i from 6 down to 0)
    if (seen contains a[i])
        first = a[i]
    else
        add a[i] to seen
    end if
end for
Print first
  1. A. 3
  2. B. 10
  3. C. 5
  4. D. -1

Correct answer: C. 5

Scanning from the right, first is overwritten every time a value already seen to the right turns up, so it ends with the repeating element whose FIRST occurrence is leftmost: 5 (index 1). 3 repeats sooner (at index 4) but first occurs later, at index 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic