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[6] = {-1, 0, 1, 2, -1, -4}
sort a                          // {-4, -1, -1, 0, 1, 2}
Integer c = 0
for (each i from 0 to 3)
    if (i > 0 AND a[i] == a[i - 1]) continue
    Integer l = i + 1, r = 5
    while (l < r)
        Integer s = a[i] + a[l] + a[r]
        if (s < 0) l = l + 1
        else if (s > 0) r = r - 1
        else
            c = c + 1
            while (l < r AND a[l] == a[l + 1]) l = l + 1
            l = l + 1
            r = r - 1
        end if
    end while
end for
Print c
  1. A. 3
  2. B. 1
  3. C. 2
  4. D. 4

Correct answer: C. 2

The sorted two-pointer scan counts DIFFERENT triples with sum 0, skipping repeated values: {−1, −1, 2} and {−1, 0, 1}. c = 2 (the two −1's do not create a second {−1, 0, 1}).

More Pseudocode and Code Tracing questions

Exams that ask this topic