📈 Next Greater Price in Stock Analysis

For each day, find the next day with a strictly higher price

🎯 Problem: Next Greater Element

Hi! I'm Teju 👋 In stock trading, we often want to know: "When will the price go higher than today?"

For each day, find the next greater price to its right. If none exists → -1

Example:
Prices: [4, 5, 2, 25]
Next Greater: 5 (for 4), 25 (for 5), 25 (for 2), -1 (for 25)

⚙️ Efficient Solution Using Stack

We traverse from right to left, maintaining a stack of prices (decreasing order).

For each price, pop smaller ones — the top of stack will be the next greater!

  1. Initialize empty stack and result array of -1
  2. Traverse prices from right to left:
    • While stack not empty and top ≤ current → POP
    • If stack empty → no greater → keep -1
    • Else → result[i] = stack top
    • PUSH current price

Time: O(N) — each element pushed/popped at most once

🎮 Interactive Demo

Enter prices and click Find Next Greater to see the algorithm in action...

📊 Stock Price Chart (Height proportional to price)

🗼 Monotonic Stack (Decreasing)

Empty Stack

🎯 Next Greater Prices