Data Structures & AlgorithmsHardProduct-company MCQ pattern

What does this function return for a = [1, 3, 3, 3, 5, 7] with x = 3 and with x = 4?

What does this function return for a = [1, 3, 3, 3, 5, 7] with x = 3 and with x = 4?
def g(a, x):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo
  1. A. 1 and 4
  2. B. 2 and 4
  3. C. 3 and 4
  4. D. 1 and 3

Correct answer: A. 1 and 4

This is a lower bound: it returns the first index whose value is ≥ x. The first 3 is at index 1, and the first value ≥ 4 is 5 at index 4. Thinking it returns 'mid when found' gives 2, the first midpoint.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic