← All lints

monotone_stack_by_hand

L0584Idiomswarn

Monotone stack by hand

while st.len > 0 and a[st.last!] < a[i]: .. st.pop(): a.next_smaller(by: x => -x)

Flagged
let n: 1..=200000 = read()
let a: [0..n]Int = read()
var st: List<Int> = []
var ans = [0..n] _ => -1
for i in 0..n:
    while st.len > 0 and a[st.last!] < a[i]:
        ans[st.pop()!] = i
    st.push(i)
print(ans)
Write instead
let n: 1..=200000 = read()
let a: [0..n]Int = read()
let next = a.next_smaller(by: x => -x)
print([next[i] ?? -1 for i in 0..n])

Why

A stack of positions popped while a[st.last!] < a[i] is the monotone stack: each popped position's answer is i, its nearest later position with a greater value. Written by hand it needs the right comparison (strict or not), the right moment to record the answer, and a sentinel for positions that never get one. a.next_smaller(by: x => -x) (std.seq) is that walk, O(n)O(n), returning a [D]?D with None for no answer; > is a.next_smaller(), <= and >= add strict: false, and prev_smaller gives the nearest earlier position. A stack of values, not positions, such as keeping an increasing subsequence, is not reported. There is no automatic fix, because the loop's answers are read in its own form (a -1 sentinel, an index shift), and that code has to change with them.

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> = []
for x in a:
    while st.len > 0 and st.last! > x:
        st.pop()
    st.push(x)
print(st)
// A stack of positions whose pops do more than record an answer (here, link a tree) is not a
// nearest-greater query.
var parent = [0..n] _ => -1
var at: List<Int> = []
for i in 0..n:
    var last = -1
    while at.len > 0 and a[at.last!] < a[i]:
        last = at.pop()!
    if last >= 0:
        parent[last] = i
    at.push(i)
print(parent)

Turn it off

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

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