惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
V
Visual Studio Blog
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
博客园 - Franky
D
DataBreaches.Net
B
Blog
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
P
Proofpoint News Feed
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Martin Fowler
Martin Fowler
月光博客
月光博客
宝玉的分享
宝玉的分享
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
F
Fortinet All Blogs
博客园 - 【当耐特】

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Next Greater Element I | Monotonic Stack
Jaspreet singh · 2026-06-26 · via DEV Community

Jaspreet singh

Problem Statement

You are given two arrays:

  • nums1 is a subset of nums2.
  • For every element in nums1, find the first greater element to its right in nums2.

If no greater element exists, return -1.


Brute Force Intuition

In an interview, you can explain it like this:

For every element in nums1, first locate its position in nums2. Then traverse towards the right until a greater element is found.

Although simple, this repeatedly scans the same elements.

Complexity

  • Time Complexity: O(N × M)
  • Space Complexity: O(1)

Brute Force Code

class Solution {

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {

        int[] ans = new int[nums1.length];

        for (int i = 0; i < nums1.length; i++) {

            int index = -1;

            // Find element in nums2
            for (int j = 0; j < nums2.length; j++) {

                if (nums2[j] == nums1[i]) {
                    index = j;
                    break;
                }
            }

            ans[i] = -1;

            // Search towards right
            for (int j = index + 1; j < nums2.length; j++) {

                if (nums2[j] > nums1[i]) {
                    ans[i] = nums2[j];
                    break;
                }
            }
        }

        return ans;
    }
}


Moving Towards the Optimal Approach

Notice that while scanning every element, we repeatedly search the right side.

Instead, can we compute the next greater element for every element in nums2 only once?

Yes!

We'll use a Monotonic Decreasing Stack.


Pattern Recognition

Whenever you see:

  • Next Greater Element
  • Previous Greater Element
  • Next Smaller Element
  • Previous Smaller Element

Think:

Monotonic Stack


Key Observation

Traverse nums2 from right to left.

Maintain a stack such that:

Top of stack
=
First Greater Element

Before pushing the current element:

Remove all smaller elements because they'll never become the next greater for future elements.


Optimal Approach

For every element:

Remove all smaller elements.

If stack becomes empty:

Next Greater = -1

Else:

Next Greater = Stack Top

Store this mapping in a HashMap.

Finally, answer each query in nums1 using the map.


Optimal Java Solution

class Solution {

    public int[] nextGreaterElement(int[] nums1, int[] nums2) {

        HashMap<Integer, Integer> map = new HashMap<>();

        Stack<Integer> st = new Stack<>();

        for (int i = nums2.length - 1; i >= 0; i--) {

            while (!st.isEmpty() && st.peek() < nums2[i]) {
                st.pop();
            }

            if (st.isEmpty()) {
                map.put(nums2[i], -1);
            } else {
                map.put(nums2[i], st.peek());
            }

            st.push(nums2[i]);
        }

        int[] ans = new int[nums1.length];

        for (int i = 0; i < nums1.length; i++) {
            ans[i] = map.get(nums1[i]);
        }

        return ans;
    }
}


Dry Run

Input

nums1 = [2,4]

nums2 = [1,2,3,4]

Traverse from right:

Step 1

Current = 4

Stack = []

Next Greater = -1

Push 4

Stack:

4


Step 2

Current = 3

Stack Top = 4

Next Greater = 4

Push 3

Stack:

3
4


Step 3

Current = 2

Stack Top = 3

Next Greater = 3

Push 2

Stack:

2
3
4


Step 4

Current = 1

Stack Top = 2

Next Greater = 2

HashMap becomes:

1 → 2

2 → 3

3 → 4

4 → -1

Answer:

2 → 3

4 → -1

Result:

[3, -1]


Why Monotonic Stack Works?

Every element enters the stack once.

Every element leaves the stack once.

The stack always maintains elements in decreasing order.

Hence:

Top of stack
=
Nearest Greater Element

without repeatedly scanning the array.


Complexity Analysis

Metric Complexity
Time Complexity O(N + M)
Space Complexity O(N)

Where:

  • N = nums2.length
  • M = nums1.length

Interview One-Liner

Traverse from right to left using a monotonic decreasing stack to precompute the next greater element for every value, then answer queries in O(1) using a HashMap.


Pattern Learned

Next Greater Element
+
Nearest Greater
+
Right Side Query

=> Monotonic Decreasing Stack

Similar Problems

  • Next Greater Element I
  • Next Greater Element II
  • Daily Temperatures
  • Stock Span Problem
  • Next Smaller Element
  • Previous Greater Element

Memory Trick

Think:

Current Element
       ↓
Remove Smaller Elements
       ↓
Stack Empty ?
       ↓
Yes → -1

No → Stack Top

Mental Model

Need Nearest Greater on Right

↓

Traverse Right to Left

↓

Maintain Decreasing Stack

↓

Top = Answer

Whenever you hear:

"Find the next greater element"

your brain should immediately think:

Monotonic Stack