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))- A. 3 -1
- B. 4 3
- C. -1 -1
- 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
- What is printed? python import bisect a = sorted(['10', '9', '100', '20']) print(a, bisect.bisectleft(a, '9'), [int(x) for x in a])
- What is printed? python def arrows(p): p = sorted(p, key=lambda x: x[1]) cnt = 0 end = None for s, e in p: if end is None or s > end: cnt…
- What is printed? python from functools import cmptokey def largest(nums): s = [str(x) for x in nums] s.sort(key=cmptokey(lambda a, b: -1…
- What is printed? python from itertools import islice, count, takewhile sq = (i i for i in count(1)) print(list(islice(sq, 3))…
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def get(n): return [n] 2 a = get(3) a.append(99) b = get(3)…
- What is printed? python from collections import Counter a = Counter('aabbbc') b = Counter('abbd') print(a - b, (a + b)['b'], sorted((a &…