ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def search(a, t):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == t:
            return mid
        if a[lo] <= a[mid]:
            if a[lo] <= t < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if a[mid] < t <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1
print(search([4, 5, 6, 7, 0, 1, 2], 0), search([4, 5, 6, 7, 0, 1, 2], 3))
  1. A. 3 -1
  2. B. 4 3
  3. C. -1 -1
  4. D. 4 -1

Correct answer: D. 4 -1

In a rotated sorted array one half is always sorted, so the code checks whether the target lies in that half. The 0 sits at index 4, and 3 is absent, so the result is -1.

More Python Programming questions

Exams that ask this topic