LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Monotonic Stack & Queue/How to Recognize Monotonic Stack Problems in 30 Seconds

How to Recognize Monotonic Stack Problems in 30 Seconds

LeetCopilot Team
Dec 22, 2025
12 min read
Monotonic StackPattern RecognitionInterview StrategyProblem SolvingLeetCode Tips
Learn the exact keywords, problem structures, and mental models to instantly identify monotonic stack problems in interviews. Includes a 10-problem recognition quiz with detailed explanations.

You have 45 minutes to solve two LeetCode mediums in your Google interview. You read the first problem. It mentions "buildings," "view," and "ocean." Do you reach for monotonic stack, or waste 15 minutes trying sliding window?

The difference between recognizing the pattern in 30 seconds versus 10 minutes is the difference between solving both problems and failing the interview.

This guide will teach you the exact keywords, problem structures, and mental models to recognize monotonic stack problems instantly—before you write a single line of code.

TL;DR

Monotonic stack keywords (instant recognition):

  • "Next greater element"
  • "Next smaller element"
  • "Previous greater/smaller"
  • "Histogram"
  • "Largest rectangle"
  • "Stock span"
  • "Visible" / "can see"
  • "Buildings" + "view"

If you see these → 95% chance it's monotonic stack

The 30-second checklist:

  1. Scan for keywords (5 seconds)
  2. Identify if it's about "next/previous" or "structure" (10 seconds)
  3. Verify it's not sliding window or two pointers (15 seconds)

The Recognition Framework

Level 1: Keyword Recognition (5 seconds)

Scan the problem for these exact phrases:

🔴 Instant Monotonic Stack Triggers:

  • "next greater"
  • "next smaller"
  • "next larger"
  • "previous greater"
  • "previous smaller"
  • "histogram"
  • "largest rectangle"
  • "stock span"

If you see any of these → Stop. It's monotonic stack. Start coding.

🟡 High Probability Triggers:

  • "visible" (buildings, people, etc.)
  • "can see"
  • "view" (ocean view, mountain view)
  • "remove K digits"
  • "trapping rain water"
  • "buildings"

If you see these → 80% chance it's monotonic stack. Verify with Level 2.

Level 2: Structure Recognition (10 seconds)

Ask: What's the core question?

Pattern A: Finding Next/Previous Element

code
"For each element, find the next element that is [greater/smaller]"
"For each element, find the previous element that is [greater/smaller]"
"How many consecutive elements to the left are [smaller/greater]?"

→ Monotonic Stack (Decreasing for "next greater", Increasing for "next smaller")

Pattern B: Range/Boundary Questions

code
"For each element, find the range where it is the [minimum/maximum]"
"Find the largest rectangle with height at least..."
"Count subarrays where element X is the [minimum/maximum]"

→ Monotonic Stack (Contribution Technique or Bidirectional Stack)

Pattern C: Structural Visibility

code
"Which buildings can see the ocean?"
"How many people can person i see?"
"Which elements are visible from the end?"

→ Monotonic Stack (Decreasing order, process right to left)

Level 3: Elimination (15 seconds)

Verify it's NOT these patterns:

❌ NOT Sliding Window if:

  • No mention of "window," "substring," or "subarray with constraint"
  • Not asking for "longest" or "shortest" contiguous segment
  • Not about maintaining a condition while expanding/shrinking

❌ NOT Two Pointers if:

  • Array is not sorted (and can't be sorted)
  • Not about finding pairs/triplets
  • Not about opposite-direction convergence

❌ NOT DP if:

  • No optimal substructure
  • No recurrence relation
  • Not about "maximum profit," "minimum cost," or "count ways"

If eliminated all above → Confirm it's monotonic stack

The Mental Model: "Next" vs "Range"

Mental Model 1: "Next" Problems

Question pattern: "For each element, what's the next element that is [greater/smaller]?"

Mental image: Standing in line, looking forward to find someone taller/shorter.

Stack behavior:

  • Maintain decreasing stack for "next greater"
  • Maintain increasing stack for "next smaller"
  • When you find the answer, pop from stack

Example keywords:

  • "next greater temperature"
  • "next smaller element"
  • "stock span" (how many days back until price was higher)

Template:

python
stack = []
for i in range(n):
    while stack and condition(nums[i], nums[stack[-1]]):
        idx = stack.pop()
        result[idx] = nums[i]  # Found the "next" for idx
    stack.append(i)

Mental Model 2: "Range" Problems

Question pattern: "For each element, find the range where it is the [min/max]."

Mental image: Each bar in a histogram, finding how far left and right it can extend.

Stack behavior:

  • Find next smaller on both sides (for histogram)
  • Calculate contribution based on range

Example keywords:

  • "largest rectangle in histogram"
  • "sum of subarray minimums"
  • "trapping rain water"

Template:

python
# Find boundaries
left = find_next_smaller_left(nums)
right = find_next_smaller_right(nums)

# Calculate based on range
for i in range(n):
    width = right[i] - left[i] - 1
    # Use width and nums[i] to calculate answer

Mental Model 3: "Visibility" Problems

Question pattern: "Which elements are visible from a certain position?"

Mental image: Standing at the end of a street, seeing which buildings are visible.

Stack behavior:

  • Maintain decreasing stack (taller buildings hide shorter ones)
  • Process right to left (or left to right depending on viewpoint)

Example keywords:

  • "buildings with ocean view"
  • "can see the sunset"
  • "visible people in a queue"

Template:

python
stack = []
# Process right to left for "view from right"
for i in range(n - 1, -1, -1):
    while stack and nums[i] >= nums[stack[-1]]:
        stack.pop()  # Current building hides shorter ones
    if not stack:
        result.append(i)  # Can see the ocean
    stack.append(i)

Keyword Dictionary

Tier 1: Instant Recognition (99% Monotonic Stack)

KeywordPatternExample Problem
"next greater element"Decreasing StackNext Greater Element I (#496)
"next smaller element"Increasing StackNext Smaller Element
"histogram"Increasing StackLargest Rectangle (#84)
"largest rectangle"Increasing StackMaximal Rectangle (#85)
"stock span"Decreasing StackOnline Stock Span (#901)

Tier 2: High Probability (80% Monotonic Stack)

KeywordPatternExample Problem
"daily temperatures"Decreasing StackDaily Temperatures (#739)
"trapping rain water"Increasing Stack or Two PointersTrapping Rain Water (#42)
"remove K digits"Increasing StackRemove K Digits (#402)
"buildings" + "view"Decreasing StackBuildings With Ocean View (#1762)
"visible"Decreasing StackFind Buildings With Ocean View

Tier 3: Context-Dependent (50% Monotonic Stack)

KeywordCheck ForAlternative
"maximum""next greater" or "histogram"Could be DP, Kadane's
"subarray""sum of minimums"Could be Prefix Sum
"window""maximum in window"Could be Sliding Window
"count""contribution technique"Could be DP, Hash Map

Common Disguises

Disguise 1: No Explicit "Next Greater"

Problem: "Daily Temperatures" (#739)

Description: "Given daily temperatures, return how many days you have to wait for a warmer temperature."

Hidden pattern: "Warmer temperature" = "next greater element"

Recognition: "Wait for warmer" → "next greater temperature"

Disguise 2: Visibility Without Saying "Next"

Problem: "Buildings With Ocean View" (#1762)

Description: "Return indices of buildings that can see the ocean (to the right)."

Hidden pattern: A building can see the ocean if no taller building is to its right.

Recognition: "Can see" + "to the right" → Decreasing stack, right to left

Disguise 3: Contribution Technique

Problem: "Sum of Subarray Minimums" (#907)

Description: "Find the sum of minimums of all subarrays."

Hidden pattern: For each element, find the range where it's the minimum.

Recognition: "Sum of minimums" + "all subarrays" → Contribution technique with stack

Disguise 4: Lexicographic Order

Problem: "Remove K Digits" (#402)

Description: "Remove K digits to make the smallest number."

Hidden pattern: Maintain increasing order, remove larger digits.

Recognition: "Remove" + "smallest number" → Monotonic increasing stack

Disguise 5: Structural Optimization

Problem: "132 Pattern" (#456)

Description: "Find if there exists i < j < k such that nums[i] < nums[k] < nums[j]."

Hidden pattern: Use monotonic stack to track potential nums[k] values.

Recognition: "Pattern" + "indices" → Complex monotonic stack

The 30-Second Recognition Process

Step 1: Keyword Scan (5 seconds)

Read the problem title and first sentence.

Look for:

  • "next"
  • "greater" / "smaller"
  • "histogram"
  • "rectangle"
  • "visible"
  • "view"
  • "span"

If found → 90% confidence it's monotonic stack. Skip to Step 3.

Step 2: Structure Analysis (10 seconds)

If no obvious keywords, read the problem description.

Ask:

  1. Is it asking about next/previous element with some property?
  2. Is it about ranges where an element is min/max?
  3. Is it about visibility or structural relationships?

If yes to any → 80% confidence. Continue to Step 3.

Step 3: Verification (15 seconds)

Eliminate other patterns:

  • Sliding Window? No "longest substring" or "window of size k"
  • Two Pointers? Array not sorted, not about pairs
  • DP? No recurrence relation or optimal substructure

If eliminated → 95% confidence. Start coding monotonic stack.

Practice Quiz: 10 Problems

For each problem, identify if it's monotonic stack in 30 seconds.

Problem 1

"Given an array, for each element, find the next element that is greater than it."

Answer

Pattern: ✅ Monotonic Stack (Decreasing)
Keyword: "next element that is greater"
Confidence: 99%
Time to recognize: 5 seconds

Problem 2

"Find the longest substring with at most K distinct characters."

Answer

Pattern: ❌ NOT Monotonic Stack (Sliding Window)
Keyword: "longest substring"
Confidence: 99% NOT stack
Time to recognize: 10 seconds

Problem 3

"Given heights of buildings, return indices of buildings that can see the sunset to the west."

Answer

Pattern: ✅ Monotonic Stack (Decreasing, right to left)
Keyword: "can see" + "buildings"
Confidence: 95%
Time to recognize: 15 seconds

Problem 4

"Find the largest rectangle in a histogram."

Answer

Pattern: ✅ Monotonic Stack (Increasing)
Keyword: "largest rectangle" + "histogram"
Confidence: 99%
Time to recognize: 5 seconds

Problem 5

"Count the number of subarrays with sum equal to K."

Answer

Pattern: ❌ NOT Monotonic Stack (Prefix Sum + Hash Map)
Keyword: "count subarrays with sum"
Confidence: 99% NOT stack
Time to recognize: 10 seconds

Problem 6

"For each day, calculate the stock price span (number of consecutive days with price ≤ today)."

Answer

Pattern: ✅ Monotonic Stack (Decreasing)
Keyword: "stock price span"
Confidence: 99%
Time to recognize: 5 seconds

Problem 7

"Remove K digits from a number to make it the smallest possible."

Answer

Pattern: ✅ Monotonic Stack (Increasing)
Keyword: "remove K digits" + "smallest"
Confidence: 90%
Time to recognize: 20 seconds

Problem 8

"Find the maximum sum of a contiguous subarray."

Answer

Pattern: ❌ NOT Monotonic Stack (Kadane's Algorithm / DP)
Keyword: "maximum sum" (not about "next greater")
Confidence: 99% NOT stack
Time to recognize: 10 seconds

Problem 9

"Calculate the sum of minimums of all subarrays."

Answer

Pattern: ✅ Monotonic Stack (Increasing, Contribution Technique)
Keyword: "sum of minimums" + "all subarrays"
Confidence: 95%
Time to recognize: 20 seconds (requires recognizing contribution technique)

Problem 10

"Given an array and a window size K, find the maximum in each sliding window."

Answer

Pattern: ⚠️ Monotonic Queue (NOT stack, use deque)
Keyword: "sliding window" + "maximum"
Confidence: 99%
Time to recognize: 10 seconds
Note: This is monotonic queue, not stack!

Recognition Mistakes to Avoid

Mistake 1: Confusing "Maximum" with "Next Greater"

Problem: "Find the maximum sum of a subarray."

Wrong thought: "Maximum" → monotonic stack

Correct thought: "Maximum sum" (not "next greater") → Kadane's Algorithm

Rule: "Maximum" alone is NOT enough. Need "next greater" or "histogram."

Mistake 2: Missing the "Next" Pattern

Problem: "Daily Temperatures"

Wrong thought: No "next greater" keyword → not monotonic stack

Correct thought: "Wait for warmer" = "next greater temperature"

Rule: Look for the concept of "next," not just the word.

Mistake 3: Confusing Stack with Queue

Problem: "Sliding Window Maximum"

Wrong thought: "Maximum" → monotonic stack

Correct thought: "Sliding window" + "maximum" → monotonic queue (deque)

Rule: If it's a sliding window, use queue (deque), not stack.

Cheat Sheet: Quick Reference

code
┌─────────────────────────────────────────────────────────┐
│ INSTANT RECOGNITION (5 seconds)                         │
├─────────────────────────────────────────────────────────┤
│ "next greater"          → Decreasing Stack              │
│ "next smaller"          → Increasing Stack              │
│ "histogram"             → Increasing Stack              │
│ "largest rectangle"     → Increasing Stack              │
│ "stock span"            → Decreasing Stack              │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ HIGH PROBABILITY (15 seconds)                           │
├─────────────────────────────────────────────────────────┤
│ "buildings" + "view"    → Decreasing Stack (R to L)     │
│ "visible"               → Decreasing Stack              │
│ "trapping rain water"   → Increasing Stack or 2-Ptr     │
│ "remove K digits"       → Increasing Stack              │
│ "sum of minimums"       → Increasing Stack (Contrib)    │
└─────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────┐
│ NOT MONOTONIC STACK                                     │
├─────────────────────────────────────────────────────────┤
│ "longest substring"     → Sliding Window                │
│ "count subarrays sum=k" → Prefix Sum + Hash Map         │
│ "maximum sum subarray"  → Kadane's Algorithm            │
│ "sorted array" + "pairs"→ Two Pointers                  │
│ "sliding window max"    → Monotonic Queue (not stack!)  │
└─────────────────────────────────────────────────────────┘

Training Strategy

Week 1: Keyword Recognition

  • Solve 10 "next greater element" problems
  • Focus on recognizing the keyword instantly
  • Time yourself: can you identify in 5 seconds?

Week 2: Disguised Problems

  • Solve "Daily Temperatures," "Buildings With Ocean View"
  • Practice recognizing the pattern without explicit keywords
  • Time yourself: can you identify in 15 seconds?

Week 3: Mixed Practice

  • Solve 20 random problems (mix of patterns)
  • For each, identify pattern BEFORE coding
  • Track accuracy: aim for 90%+

Week 4: Speed Drills

  • Read 50 problem descriptions
  • Identify pattern in 30 seconds each
  • Don't code, just identify
  • Review mistakes

Conclusion

Pattern recognition is a trainable skill. With this framework, you can identify monotonic stack problems in 30 seconds or less.

The 30-second process:

  1. Keyword scan (5s): "next greater," "histogram," "visible"
  2. Structure analysis (10s): Is it about next/previous or ranges?
  3. Elimination (15s): Not sliding window, two pointers, or DP?

Key recognition triggers:

  • Instant: "next greater," "histogram," "stock span"
  • High probability: "buildings + view," "visible," "remove K digits"
  • Hidden: "warmer temperature," "can see," "sum of minimums"

Common mistakes:

  • ❌ "Maximum" alone doesn't mean monotonic stack
  • ❌ "Sliding window maximum" is monotonic queue, not stack
  • ❌ Look for the concept of "next," not just the word

Practice strategy:

  1. Solve 10 problems per pattern
  2. Identify pattern BEFORE coding
  3. Time yourself: 30 seconds or less
  4. Review mistakes and understand why

Master this recognition framework, and you'll never waste interview time on the wrong pattern again.

Next steps:

Next time you see "next greater element," you'll know in 5 seconds: monotonic stack.

Want to Practice LeetCode Smarter?

LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.

Also compatible with Edge, Brave, and Opera

Related Tutorials