← All lints

sliding_min_by_hand

L0566Idiomswarn

Sliding-window minimum kept with a hand-written deque

while dq.len > head and a[dq[dq.len - 1]] >= a[i]: dq.pop(): Window(min)

Flagged
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var dq: List<Int> = []
var head = 0
var out: List<Int> = []
for i in 0..n:
    while dq.len > head and a[dq.last!] >= a[i]:
        dq.pop()
    dq.push(i)
    if dq[head] <= i - k:
        head += 1
    if i >= k - 1:
        out.push(a[dq[head]])
print(out)
Write instead
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var w = Window(min)
var out: List<Int> = []
for i in 0..n:
    w.push(a[i])
    if i >= k:
        w.pop()
    if i >= k - 1:
        out.push(w.all!)
print(out)

Why

A deque of positions whose values only increase, popped at the back while the newest value is no larger and advanced at the front once its position falls out of the window, gives each window's minimum in O(1)O(1) amortized time. Written by hand it is a list, a head index, two comparisons that must agree on >= or >, and an off-by-one in i - k. Window(min) from std.window keeps that deque for you: w.push(x) when an item enters, w.pop() when the oldest leaves, and w.all! is the minimum of what is in it. Window(max) gives the maximum, and any other fold works too (Window(+) keeps a running sum). There is no automatic fix, since the window's bounds move with the loop. A monotone stack with no window (the previous smaller element) 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()
let a: [0..n]Int = read()
var st: List<Int> = []
var prev: List<Int> = []
for i in 0..n:
    while st.len > 0 and a[st[st.len - 1]] >= a[i]:
        st.pop()
    prev.push(if st.len > 0: st[st.len - 1] else: -1)
    st.push(i)
print(prev)

Turn it off

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

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