ProgrammingModerateAmazon OA · Flipkart coding round
A solution must answer q = 2 * 10^5 queries of the form 'how many values in array A are at most x', with A of length n = 2 * 10^5 that never changes. Which Python approach is best?
- A. Build a new sorted list in every query using sorted(A)
- B. Use a list of all values, then call A.index(x) per query
- C. Sort A once, then use bisect_right per query for O(log n) each
- D. Call sum(v <= x for v in A) for each query
Correct answer: C. Sort A once, then use bisect_right per query for O(log n) each
Sorting once costs O(n log n), and bisect answers each query in O(log n), giving about O((n + q) log n) overall. Scanning A per query costs O(n q), which is too slow.
More Python Programming questions
- A program builds a long output string with s = s + str(i) + ' ' for each of n = 2 10^5 values i. Which change is the standard fix for…
- What is printed? python rows = [('bob', 90), ('amy', 90), ('cat', 75)] rows.sort(key=lambda r: (-r[1], r[0])) print([r[0] for r in rows])
- What is printed? python print([1, 2] < [1, 2, 0], (1, 2) < (1, 2, 0), 'abc' < 'abd', [2] < [1, 9])
- What is printed? python x = [1, 2, 3, 4] y = x x = x + [5] x.append(6) y.append(9) print(len(x), len(y), y is x)
- What is printed? python from collections import Counter c = Counter([3, 1, 3, 2, 1, 3]) print(c.mostcommon(1), sorted(c.elements()), c[7])
- What is printed? python from math import comb print(comb(5, 2), comb(5, 7), comb(0, 0), comb(3, 1) comb(3, 1))