ProgrammingModerateTCS CodeVita · Infosys HackWithInfy
A program must answer 10^5 range-sum queries over an array of 10^5 numbers in CPython. Which approach is fastest?
- A. Call sum(a[l:r]) for each query, which is O(n) per query
- B. Build prefix sums once, then answer each query in O(1)
- C. Sort the queries and the array together for each query
- D. Build a new set for each query and add the range values
Correct answer: B. Build prefix sums once, then answer each query in O(1)
A prefix-sum array costs O(n) to build and gives each range sum as pre[r] - pre[l-1] in O(1). Slicing per query costs O(n), which is about 10^10 steps overall.
More Python Programming questions
- What is printed? python from functools import lrucache class C: @lrucache(maxsize=None) def f(self, x): return x 2 a, b = C(), C() a.f(1)…
- What is printed? python class A: def init(self, v): self.v = v def eq(self, o): return isinstance(o, A) and self.v == o.v xs = [A(1)…
- What is printed? python a, b = 5, 9 a ^= b b ^= a a ^= b print(a, b)
- What is printed? python nums = [10, 9, 100, 1] print(sorted(nums, key=str), max(nums, key=str), sorted(map(str, nums))[-1])
- What is printed? python def ngecirc(a): n = len(a) res = [-1] n st = [] for i in range(2 n): x = a[i % n] while st and a[st[-1]] < x…
- What is printed? python def dsum(n): return n if n < 10 else dsum(sum(map(int, str(n)))) print(dsum(9875), dsum(0), dsum(999999999999))