Data Structures & AlgorithmsHardProduct company OA

In a Fenwick (binary indexed) tree of size 16 (1-based), the update at index 5 adds the value to i = 5 and then repeatedly does i += i & (−i) while i ≤ 16. Which indices are updated?

  1. A. 5, 6, 8, 16
  2. B. 5, 6, 7, 8
  3. C. 5, 4, 0
  4. D. 5, 7, 8, 16

Correct answer: A. 5, 6, 8, 16

i & (−i) is the lowest set bit: 5 (0101) + 1 = 6; 6 (0110) + 2 = 8; 8 + 8 = 16; 16 + 16 = 32 > 16, stop. Each of those nodes covers a range that contains index 5. '5, 4, 0' is the QUERY direction (i −= i & −i).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic