← All lints

diff_by_hand

L0559Idiomswarn

Difference array by hand

d[l] += x; d[r] -= x: Diff<D, T>() with add(l..r, x) and finish()

Flagged
let (n, q): (1..=100000, 1..=100000) = read()
var d: List<Int> = [0 for _ in 0..=n]
for _ in 0..q:
    let (l, r, x): (1..=n, 1..=n, Int) = read()
    d[l - 1] += x
    d[r] -= x
print(d)
Write instead
let (n, q): (1..=100000, 1..=100000) = read()
domain D = 0..n
var d = Diff<D, Int>()
for _ in 0..q:
    let (l, r, x): (1..=n, 1..=n, Int) = read()
    d.add(D(l - 1)..=D(r - 1), x)
print(d.finish())

Why

Adding x at the start of a range and subtracting it just past the end, then taking prefix sums, is a difference array: the end index (r or r + 1?) and the extra slot are where it goes wrong. Diff<D, T>() from std.prefix is one: d.add(l..r, x) takes the range as a range, and d.finish() returns the table, in O(1)O(1) per update and O(n)O(n) to finish. There is no automatic fix, because the prefix pass that follows goes with it.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let (n, q): (1..=100000, 1..=100000) = read()
var d: List<Int> = [0 for _ in 0..=n]
for _ in 0..q:
    let (l, r, x): (1..=n, 1..=n, Int) = read()
    d[l - 1] += x
    d[r] -= x + 1
print(d)

Turn it off

For one block, wrap it in with lint(diff_by_hand: allow):. For a project, add diff_by_hand = "allow" under [lints] in cp.toml.

Generated from spec/lints/diff_by_hand, the same record the linter is built from.