← All lints

inversions_by_fenwick

L0569Idiomswarn

Inversions counted with a Fenwick tree by hand

inv += i - bit.prefix(x); bit.add(x, 1): inversions(xs)

Flagged
let n: 1..=200000 = read()
domain I = 0..n
let a: [I]1..=1e9 = read()
let (domain C, comp) = compress(a)
var bit = Fenwick<C, Int>()
var inv = 0
for i in I:
    let id = comp.at(a[i])
    inv += i.to_idx - bit.prefix(id.r)
    bit.add(id, 1)
print(inv)
Write instead
let n: 1..=200000 = read()
let a: [0..n]1..=1e9 = read()
print(inversions(a))

Why

Compressing the values, then walking left to right and adding "items so far minus those not above this one" from a Fenwick tree of counts, is the textbook inversion count. Written by hand it needs the compression, the tree, the right cut (<= or < decides whether ties count) and the position arithmetic. inversions(xs) from std.seq counts the pairs i < j with xs[i] > xs[j] (ties are not inversions) in O(nlog⁡n)O(n \log n) on any sequence, with no compression. There is no automatic fix, since the count may be one step of a larger computation. A Fenwick loop that keeps per-item counts rather than summing an inversion count is not reported.

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: 1..=200000 = read()
domain I = 0..n
let a: [I]1..=1e9 = read()
let (domain C, comp) = compress(a)
var bit = Fenwick<C, Int>()
var smaller: List<Int> = []
for i in I:
    let id = comp.at(a[i])
    smaller.push(bit.prefix(id.l))
    bit.add(id, 1)
print(smaller)

Turn it off

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

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