ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; arrays are indexed from 0)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; arrays are indexed from 0)
Integer a[6] = {1, 3, 3, 3, 5, 7}, x = 3
Integer lo = 0, hi = 6, mid
while (lo < hi)
    mid = (lo + hi) / 2
    if (a[mid] < x) lo = mid + 1 else hi = mid
end while
Integer first = lo
lo = 0
hi = 6
while (lo < hi)
    mid = (lo + hi) / 2
    if (a[mid] <= x) lo = mid + 1 else hi = mid
end while
Print first, lo, lo - first
  1. A. 1 3 2
  2. B. 1 4 3
  3. C. 2 4 2
  4. D. 0 4 4

Correct answer: B. 1 4 3

The first search finds the first index with a value ≥ 3 (lower bound): 1. The second finds the first index with a value > 3 (upper bound): 4. Their difference is the number of 3's: 1 4 3.

More Pseudocode and Code Tracing questions

Exams that ask this topic