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?- A. [3, 2, 0, -2, 0, -3]
- B. [3, 5, 5, 2, 1, -1]
- C. [3, 5, 5, 1, 1, 0]
- 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
- Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one…
- Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays…
- Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k)…
- Problem: A DP table for a 2 × 3 grid is created in two ways and one cell is set in each. python dp = [[0] 3] 2 dp[0][1] = 5 dp2 = [[0] 3…
- Problem: Count the contiguous subarrays with an ODD sum using prefix-sum parity counts. python def oddsumsubarrays(a): even, odd, run, res…
- Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid…