ProgrammingModerateTCS NQT · Accenture
A sorted array holds 10^6 integers and receives 10^5 queries asking how many values are at most x. Which approach is fastest in CPython?
- A. Scan the whole array for each query, about 10^11 comparisons
- B. Use bisect_right on the sorted array per query, about 2 x 10^6 steps
- C. Sort the array again for each query, about 10^11 steps
- D. Build a new set of values for each query, about 10^11 steps
Correct answer: B. Use bisect_right on the sorted array per query, about 2 x 10^6 steps
bisect_right finds the count of values not above x in O(log n) per query, so 10^5 queries cost about 2 x 10^6 steps. Scanning or re-sorting each time costs about 10^11.
More Python Programming questions
- What is printed? python def depth(n): return 0 if n == 0 else 1 + depth(n - 1) try: print(depth(500)) print(depth(5000)) except…
- What is printed? python from collections import defaultdict d = defaultdict(list) d['a'].append(1) print('b' in d, d['b'], len(d), 'b' in d)
- What is printed? python m = [[1, 2, 3], [4, 5, 6]] rot = [list(r) for r in zip(m[::-1])] print(rot)
- What is printed? python def hist(h): st = [] best = 0 h = h + [0] for i, x in enumerate(h): start = i while st and st[-1][1] >= x: idx…
- What is printed? python def knap(items, cap): dp = [0] (cap + 1) for w, v in items: for c in range(cap, w - 1, -1): dp[c] = max(dp[c]…
- What is printed? python from collections import deque def knight(src, dst): seen = {src: 0} q = deque([src]) moves = [(1, 2), (2, 1), (-1…