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

推荐订阅源

J
Java Code Geeks
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
N
Netflix TechBlog - Medium
阮一峰的网络日志
阮一峰的网络日志
H
Help Net Security
I
InfoQ
月光博客
月光博客
量子位
Blog — PlanetScale
Blog — PlanetScale
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
Engineering at Meta
Engineering at Meta
G
Google Developers Blog
D
DataBreaches.Net
宝玉的分享
宝玉的分享
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
人人都是产品经理
人人都是产品经理

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