← All lints

lca_by_hand

L0555Idiomswarn

Lowest common ancestor by hand

while depth[u] > depth[v]: u = parent[u]: Rooted.lca

Flagged
let n: 2..=1000 = read()
var parent: List<Int> = [0]
var depth: List<Int> = [0]
for v in 1..n:
    let p: 0..v = read()
    parent.push(p)
    depth.push(depth[p] + 1)
let (u0, v0): (0..n, 0..n) = read()
var u = u0
var v = v0
while depth[u] > depth[v]:
    u = parent[u]
while depth[v] > depth[u]:
    v = parent[v]
while u != v:
    u = parent[u]
    v = parent[v]
print(u)
Write instead
domain V = 0..4
let par: [V]?V = [None, Some(0), Some(0), Some(1)]
let t = Rooted.from_parents(par)
print(t.lca(3, 2))

Why

Lifting the deeper vertex by its parent until the depths match, then both together until they meet, finds the lowest common ancestor in time proportional to the depth: fine once, too slow for many queries on a path-shaped tree. A Rooted tree from std.tree (Rooted(adj, root: r) or Rooted.from_parents(par)) answers t.lca(u, v), t.dist(u, v) and t.ancestor(v, k) in O(log⁡n)O(\log n). There is no automatic fix, since the tree has to be built as a Rooted first.

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: 2..=1000 = read()
var parent: List<Int> = [0]
var depth: List<Int> = [0]
for v in 1..n:
    let p: 0..v = read()
    parent.push(p)
    depth.push(depth[p] + 1)
let (u0, v0): (0..n, 0..n) = read()
var u = u0
while depth[u] > depth[v0]:
    u = parent[v0]
print(u)

Turn it off

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

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