Data Structures & AlgorithmsVery hardCodeforces Div2 D · data structures

Problem: A Fenwick tree of size 8 receives point adds (1,+5), (3,+2), (5,+7), (8,+1) with the usual add and prefix-query code, then prints prefix(4) and prefix(8) - prefix(4). What two numbers are printed?

Problem: A Fenwick tree of size 8 receives point adds (1,+5), (3,+2), (5,+7), (8,+1) with the usual add and prefix-query code, then prints prefix(4) and prefix(8) - prefix(4). What two numbers are printed?
n = 8
t = [0] * (n + 1)
def add(i, v):
    while i <= n:
        t[i] += v
        i += i & -i
def q(i):
    s = 0
    while i > 0:
        s += t[i]
        i -= i & -i
    return s
for i, v in [(1, 5), (3, 2), (5, 7), (8, 1)]:
    add(i, v)
print(q(4), q(8) - q(4))
What is printed?
  1. A. 7 15
  2. B. 12 8
  3. C. 7 9
  4. D. 7 8

Correct answer: D. 7 8

The prefix sum up to 4 is 5 + 2 = 7, and the sum over positions 5 to 8 is 7 + 1 = 8. Confusing the lowbit step with i += 1 changes the output.

More Coding Interview Problems questions

Exams that ask this topic