# Why does this monotonic stack return the wrong next greater values for duplicate elements?

**URL:** <https://forum.kirupa.com/t/why-does-this-monotonic-stack-return-the-wrong-next-greater-values-for-duplicate-elements/679943>\
**Category:** web dev\
**Created:** [April 3, 2026, 6:00pm UTC](https://forum.kirupa.com/t/why-does-this-monotonic-stack-return-the-wrong-next-greater-values-for-duplicate-elements/679943 "2026-04-03T18:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ellen1979](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/ellen1979/32/31260_2.png) [@Ellen1979](https://forum.kirupa.com/u/Ellen1979)\
**Post date:** [April 3, 2026, 6:00pm UTC](https://forum.kirupa.com/t/why-does-this-monotonic-stack-return-the-wrong-next-greater-values-for-duplicate-elements/679943/1 "2026-04-03T18:00:11Z")

</div>

I’m implementing next greater element with a monotonic stack, but duplicates seem to break it. For input `[2, 2, 3]` I expect `[3, 3, -1]`, yet I get `[-1, 3, -1]`. I think my map is overwriting something, but I’m not sure what the right fix is without losing O(n).

```js
function nextGreater(nums) {
  const st = [], ans = new Map();
  for (const x of nums) {
    while (st.length && st[st.length - 1] < x) {
      ans.set(st.pop(), x);
    }
    st.push(x);
  }
  return nums.map(x => ans.get(x) ?? -1);
}
console.log(nextGreater([2, 2, 3]));

```

Should I be storing indices instead of values here?

Ellen

---

<div class="post-metadata">

**Author:** ![ArthurDent](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/arthurdent/32/31262_2.png) [@ArthurDent](https://forum.kirupa.com/u/ArthurDent)\
**Post date:** [April 3, 2026, 6:14pm UTC](https://forum.kirupa.com/t/why-does-this-monotonic-stack-return-the-wrong-next-greater-values-for-duplicate-elements/679943/2 "2026-04-03T18:14:06Z")

</div>

Yes, store indices, because `Map(value -> nextGreater)` collapses both `2`s into one bucket and duplicates are where the gremlin lives.

Arthur
