Handle no greater as a sentinel
Updated
Initialize answer[i] = sentinel (−1, n, or null). Leftover indices in the stack never found a greater or smaller. The sentinel is the documented none, not a legal index you later dereference by accident.
What to focus on
Do not leave answer uninitialized. Do not use 0 as sentinel if 0 is a legal value or index. After the scan, drain the stack writing sentinels, or have prefilled them.
Worked examples
prefill
a = [2, 1, 3], answer starts [-1,-1,-1]- writes overwrite 1 and 0
- index 2 stays -1
Result: [3, 3, -1]
all sentinel
a = [3, 2, 1]- no overwrites
Result: [-1, -1, -1]
empty
a = []- no answers
Result: []
Try it
Write nextGreater(a). a is an array of integers. Prefill answer with -1. Run next-greater. Do not use 0 as none for indices. a = [2, 1, 3], answer starts [-1,-1,-1] → [3, 3, -1]. a = [3, 2, 1] → [-1, -1, -1]. a = [] → [].
a is a list of integers and may be empty. Sentinel is -1. Strictly greater.