Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (difference array for range increments)

What is printed? (difference array for range increments)
n = 6
diff = [0] * (n + 1)
for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5, -2)]:
    diff[l] += v; diff[r + 1] -= v
a, run = [], 0
for i in range(n):
    run += diff[i]; a.append(run)
print(a)
  1. A. [5, 8, 8, 1, 1, -2]
  2. B. [5, 8, 8, 3, 3, -2]
  3. C. [5, 8, 8, 1, 1, 0]
  4. D. [5, 3, 0, -2, 0, 2]

Correct answer: A. [5, 8, 8, 1, 1, -2]

Each range update touches two cells of the difference array; a final prefix sum rebuilds the values. Index 3: +3 − 2 = 1; index 5: −2 only. O(1) per update and O(n) to rebuild, instead of O(length) per update.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic