Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based, inclusive). Commands are applied with a difference array and one prefix-sum pass.

Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based, inclusive). Commands are applied with a difference array and one prefix-sum pass.
def apply(n, cmds):
    d = [0] * (n + 1)
    for l, r, v in cmds:
        d[l] += v
        d[r + 1] -= v
    out, run = [], 0
    for i in range(n):
        run += d[i]
        out.append(run)
    return out
print(apply(6, [(0, 2, 3), (1, 4, 2), (3, 5, -1)]))
What is printed?
  1. A. [3, 2, 0, -2, 0, -3]
  2. B. [3, 5, 5, 2, 1, -1]
  3. C. [3, 5, 5, 1, 1, 0]
  4. D. [3, 5, 5, 1, 1, -1]

Correct answer: D. [3, 5, 5, 1, 1, -1]

Each command touches only two cells: +v at l and −v at r + 1. Difference array: [3, 2, 0, −3, 0, −2, 1]. Prefix sums: 3, 5, 5, 2 − 1 = 1, 1, −1. The last option is the raw difference array before the prefix pass. Total O(n + q) instead of O(n·q).

More Coding Interview Problems questions

Exams that ask this topic