Back to Practice
#0131

Next Greater Element

MediumDSA25 min20 XP

Problem

Given nums, return a list where each position contains the next greater value to its right, or -1 if none exists.

Why This Matters

This is the base monotonic-stack problem behind stock span, temperatures, and histogram tasks.

Function Signature

def next_greater(nums):

Examples

Example 1
Input[2, 1, 3, 2]
Output[3, 3, -1, -1]

3 is the next greater value for both 2 and 1.

Constraints

  • Return the exact requested structure.
  • Handle normal edge cases cleanly.
  • Prefer readable code over clever shortcuts.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input[2, 1, 3, 2]
Expected[3, 3, -1, -1]

3 is the next greater value for both 2 and 1.

Hidden Test Categories
strictly decreasingstrictly increasingequal values