ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0)

What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[4] = {3, 4, -1, 1}, n = 4
for (each i from 0 to n - 1)
    while (a[i] >= 1 AND a[i] <= n AND a[a[i] - 1] != a[i])
        swap(a[i], a[a[i] - 1])
    end while
end for
Integer ans = n + 1
for (each i from 0 to n - 1)
    if (a[i] != i + 1)
        ans = i + 1
        break
    end if
end for
Print ans
  1. A. 5
  2. B. 2
  3. C. 1
  4. D. 4

Correct answer: B. 2

The swaps put each value v in 1..n at index v − 1, giving {1, −1, 3, 4}. The first index whose value is wrong is 1, so the smallest missing positive is 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic