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

推荐订阅源

U
Unit 42
L
LangChain Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
有赞技术团队
有赞技术团队
B
Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
Martin Fowler
Martin Fowler
H
Hackread – Cybersecurity News, Data Breaches, AI and More
M
MIT News - Artificial intelligence
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
博客园 - Franky
小众软件
小众软件

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
Min Stack
Jaspreet singh · 2026-06-28 · via DEV Community

Jaspreet singh

Problem Statement

Design a stack that supports the following operations in O(1) time:

push(x)

pop()

top()

getMin()

getMin() should always return the minimum element currently present in the stack.


Brute Force Intuition

In an interview, you can explain it like this:

We can use a normal stack. Whenever getMin() is called, simply traverse the entire stack and find the minimum element.

This works, but every getMin() requires scanning all elements.

Complexity

Operation Complexity
push O(1)
pop O(1)
top O(1)
getMin O(N)

Brute Force Code

class MinStack {

    Stack<Integer> st;

    public MinStack() {
        st = new Stack<>();
    }

    public void push(int val) {
        st.push(val);
    }

    public void pop() {
        st.pop();
    }

    public int top() {
        return st.peek();
    }

    public int getMin() {

        int min = Integer.MAX_VALUE;

        for (int num : st) {
            min = Math.min(min, num);
        }

        return min;
    }
}


Moving Towards the Optimal Approach

The problem is:

Finding Minimum

Instead of searching every time,

why not store the minimum while inserting elements?

Maintain another stack that stores:

Current Minimum

at every stage.


Pattern Recognition

Whenever you see:

  • Stack
  • Current Minimum / Maximum
  • O(1) Query

Think:

Two Stacks


Key Observation

Main Stack:

5

2

8

1

Min Stack:

5

2

2

1

Top of Min Stack always stores:

Minimum Element


Optimal Approach

Push

Push into main stack.

If:

Current element <= current minimum

also push into min stack.


Pop

If popped element equals:

Minimum

remove from min stack too.


getMin()

Simply return:

Top of Min Stack


Optimal Java Solution

class MinStack {

    Stack<Integer> stack;
    Stack<Integer> minStack;

    public MinStack() {

        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {

        stack.push(val);

        if (minStack.isEmpty()
            || val <= minStack.peek()) {

            minStack.push(val);
        }
    }

    public void pop() {

        if (stack.peek().equals(minStack.peek())) {
            minStack.pop();
        }

        stack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}


Dry Run

Operations

push(5)

Main Stack:

5

Min Stack:

5


push(2)

Main:

2
5

Min:

2
5


push(8)

Main:

8
2
5

Min:

2
5

Minimum:

2


push(1)

Main:

1
8
2
5

Min:

1
2
5

Minimum:

1


pop()

Remove:

1

Main:

8
2
5

Min:

2
5

Minimum:

2


Why Two Stacks Work?

Every minimum value is stored separately.

Whenever the minimum element is removed:

Remove it from Min Stack too.

Thus:

Top of Min Stack

=

Current Minimum

without scanning the stack.


Complexity Analysis

Operation Complexity
Push O(1)
Pop O(1)
Top O(1)
Get Min O(1)

Follow-Up (Optimal Space)

Instead of maintaining two stacks,

we can use:

One Stack

+

One Variable (min)

using an encoding technique.

This reduces auxiliary space while keeping all operations O(1).


Interview One-Liner

Maintain a second stack that stores the minimum element seen so far. The top of the second stack always represents the current minimum.


Pattern Learned

Stack

+

Need Current Minimum

↓

Extra Stack

Similar Problems

  • Min Stack
  • Max Stack
  • Stock Span
  • Daily Temperatures
  • Largest Rectangle in Histogram

Memory Trick

Think:

Push

↓

Is New Minimum?

↓

Yes

↓

Push into Min Stack

Pop

↓

Removing Minimum?

↓

Pop from Min Stack

Mental Model

Main Stack

Stores All Values

↓

Min Stack

Stores Running Minimum

Whenever you hear:

"Design a stack supporting getMin() in O(1)"

your brain should immediately think:

Two Stacks (Main Stack + Min Stack)