ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0; abs gives the absolute value)

What will be the output of the following pseudocode? (Arrays are indexed from 0; abs gives the absolute value)
Integer a[8] = {4, 3, 2, 7, 8, 2, 3, 1}
for (each i from 0 to 7)
    Integer v = abs(a[i])
    if (a[v - 1] < 0)
        Print v
    else
        a[v - 1] = -a[v - 1]
    end if
end for
  1. A. 2 3
  2. B. 3 2
  3. C. 2 3 1
  4. D. 4 7

Correct answer: A. 2 3

Visiting value v flips the sign at index v − 1; finding it already negative means v was seen before. The second 2 is at index 5 and the second 3 at index 6, so the duplicates come out as 2 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic