ProgrammingHardTCS NQT · Infosys
A program must answer 10^5 range-sum queries on an array of 10^5 ints within a 1 second limit. Which approach is fast enough?
- A. Recompute the sum with a loop for each query, about 10^10 steps
- B. Bubble-sort the array before each query
- C. Build prefix sums once in O(N), then answer each query in O(1)
- D. Use a recursion that re-sums the left half for every query
Correct answer: C. Build prefix sums once in O(N), then answer each query in O(1)
Per-query loops need about 10^10 additions, far beyond the limit. A prefix array built once answers each query with a single subtraction, for O(N + Q) total work.
More C Programming questions
- Using fast exponentiation with reduction modulo 1000000007 after each multiplication, what is 2^100 mod 1000000007?
- int n = -1; uint64t u = (uint64t)n; What is u?
- uint32t fib(int n) iteratively computes a = 0, b = 1, then n times: t = a + b; a = b; b = t, with all arithmetic in uint32t. What is…
- int x = 5; x = x++; What is the outcome of this statement?
- uint16t h = 0; for each character c of "ABCDE", h = h 31 + c; with 65 for 'A' and so on. What is h at the end?
- Which function correctly tests whether an unsigned value x is a power of two, with x = 0 excluded?