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?- A. 7 15
- B. 12 8
- C. 7 9
- 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
- Problem: You want the maximum number of non-overlapping intervals. Which greedy rule is provably optimal?
- Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3]. python from collections import Counter def cnt(a): seen =…
- Problem: What does the following print? python print([format(i ^ (i >> 1), '03b') for i in range(4)])
- Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3]. python def count(a, T): a = sorted(a) i, j = 0…
- Problem: Mo's algorithm answers q range queries on an array of length n by sorting queries into blocks of size about sqrt(n) and moving…
- Problem: In a segment tree with lazy propagation, what is the cost of one range-add update on an array of length n?