ProgrammingModerateAmazon OA · Flipkart coding round
Which technique gives the lowest total cost for answering q range-sum queries on a fixed Python list of length n, where n and q are both 2 * 10^5?
- A. Sort the list before each query so that bisect can answer the sum
- B. Keep the list as a set and use len() to get the sum of elements
- C. Build a prefix-sum list once in O(n), then answer each query in O(1) by subtracting two prefix values
- D. Call sum(a[l:r]) for each query, because slicing is O(1)
Correct answer: C. Build a prefix-sum list once in O(n), then answer each query in O(1) by subtracting two prefix values
Prefix sums cost O(n) to build and O(1) per query, for O(n + q) total. Slicing copies the elements, so sum(a[l:r]) costs O(r - l) per query.
More Python Programming questions
- What is printed? python x = 7 print(x // 2 if x % 2 else x / 2, x > 3 > 2, not x > 3 == 4)
- What is printed? python print(pow(-2, 3, 5), pow(3, -1, 7), pow(2, 10, -7), (-2) 3 % 5)
- What is printed? python try: s = str(10 4301) print(len(s)) except ValueError: print('too many digits')
- What is printed? python print(' xt'.strip() == 'x', 'atb'.expandtabs(4), len('atb'.expandtabs(4)), 'abrncd'.splitlines())
- What is printed? python print('²'.isdigit(), '²'.isdecimal(), '²'.isnumeric(), '٥'.isdecimal())
- What is printed? python print(len('é'.encode('utf-8')), len('é'.encode('utf-16-le')), len('a€'.encode()), b'xc3xa9'.decode())