ProgrammingHardAmazon OA · Flipkart coding round
Which Python construct is the most efficient way to test whether a sorted list `a` contains x in O(log n) time without building extra structures?
- A. x in a, because the in operator on lists uses binary search
- B. a.index(x), because index stops early on sorted data
- C. sum(1 for v in a if v == x), which is O(log n) on a sorted list
- D. bisect.bisect_left(a, x) followed by an equality check at that index
Correct answer: D. bisect.bisect_left(a, x) followed by an equality check at that index
bisect_left finds the first position where x could go in O(log n). Checking that the value at the position equals x confirms membership. The plain in operator and index are linear scans.
More Python Programming questions
- Which of the following problems can be solved correctly by a greedy algorithm that sorts by end time, when given the intervals and asked…
- What is printed? python a = [1, 2, 3, 4, 5, 6] print(a[1::2], a[::-2], a[4:1:-1])
- What is printed? python s = 'a1b22c333' import re print(re.findall(r'd+', s), sum(int(x) for x in re.findall(r'd+', s)))
- What is printed? python def solve(n, memo={}): if n in memo: return memo[n] if n < 2: return n memo[n] = solve(n - 1) + solve(n - 2)…
- What is printed? python x = 7 match x: case 1 | 2: r = 'small' case int(v) if v > 5: r = f'big{v}' case : r = 'other' print(r)
- What is printed? python a = [[1, 2], [3]] b = a[:] b[1].append(4) b.append([5]) print(a, b, len(a))