Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed).
Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed).
int n = 8; vector<long long> t(n + 1, 0);
void add(int i, long long v) { for (; i <= n; i += i & -i) t[i] += v; }
long long pre(int i) { long long s = 0; for (; i > 0; i -= i & -i) s += t[i]; return s; }
// values 5, 2, 9, -3, 4, 1, 7, 6 added at positions 1..8, then add(4, 10)
// cout << pre(4) << " " << pre(7) - pre(2) << " " << t[8];What is printed?- A. 13 28 41
- B. 23 28 41
- C. 23 18 41
- D. 23 28 31
Correct answer: B. 23 28 41
i & −i is the lowest set bit, which gives each node's range length. After adding 10 at position 4 the array is 5, 2, 9, 7, 4, 1, 7, 6: prefix(4) = 23, positions 3..7 sum to 28, and t[8] covers all 8 positions = 41. Both operations are O(log n).
More Coding Interview Problems questions
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…