MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Monotonic Stacks: Next Greater Element & Histogram Area Patterns0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
4.1Stacks: LIFO Operations, Array/List Implementations & Bracket Matching4.2Monotonic Stacks: Next Greater Element & Histogram Area Patterns4.3Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)4.4Hash Tables: Hash Functions, Separate Chaining & Open Addressing4.5Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums
HomeTutorialsData Structures & AlgorithmsMonotonic Stacks: Next Greater Element & Histogram Area Patterns
Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)

Monotonic Stacks: Next Greater Element & Histogram Area Patterns

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

A Monotonic Stack is a specialized stack whose elements are strictly maintained in a sorted monotonic order—either strictly increasing or strictly decreasing. This pattern is the secret weapon for solving range-lookup problems (like Next Greater Element, Daily Temperatures, and Largest Rectangle in Histogram) in single-pass $O(n)$ linear time instead of brute-force $O(n^2)$.


1. Real-World Analogy: Waiting for a Taller Person

Imagine people standing in a line waiting at a bus stop:

  • A person looks forward into the distance.
  • Shorter people in front of them are completely blocked from view by the first person who is taller than them.
  • Once a giant steps into the line, all shorter people standing behind them are overshadowed. A monotonic decreasing stack maintains this exact line of sight!

2. The Two Types of Monotonic Stacks

  1. 1
    Monotonically Increasing Stack: Elements from bottom to top are in increasing order ($1 \to 3 \to 5 \to 8$).
  • Used to find the Previous/Next Smaller Element.
  1. 1
    Monotonically Decreasing Stack: Elements from bottom to top are in decreasing order ($8 \to 5 \to 3 \to 1$).
  • Used to find the Previous/Next Greater Element.
1Algorithm Rule for Monotonic Decreasing Stack (Next Greater Element):
2Before pushing element X:
3While stack is not empty AND stack.top() < X:
4 pop() element (because X is the "Next Greater Element" for the popped item!)
5push(X)

3. Classic Problem: Daily Temperatures

Given an array of daily temperatures temperatures, return an array answer such that answer[i] is the number of days you have to wait after the $i$-th day to get a warmer temperature. If there is no future day with a warmer temperature, keep answer[i] == 0.

Python 3 Implementation:

1def daily_temperatures(temperatures: list[int]) -> list[int]:
2 n = len(temperatures)
3 result = [0] * n
4 stack = [] # Stores INDICES: [index, ...]
5
6 for current_day, current_temp in enumerate(temperatures):
7 # Pop days whose temperatures are cooler than today's temperature!
8 while stack and temperatures[stack[-1]] < current_temp:
9 prev_day = stack.pop()
10 result[prev_day] = current_day - prev_day
11
12 stack.append(current_day)
13
14 return result

Modern JavaScript / TypeScript Implementation:

1export function dailyTemperatures(temperatures: number[]): number[] {
2 const n = temperatures.length;
3 const result: number[] = new Array(n).fill(0);
4 const stack: number[] = []; // Stores indices
5 
6 for (let currentDay = 0; currentDay < n; currentDay++) {
7 const currentTemp = temperatures[currentDay];
8 
9 while (stack.length > 0 && temperatures[stack[stack.length - 1]] < currentTemp) {
10 const prevDay = stack.pop()!;
11 result[prevDay] = currentDay - prevDay;
12 }
13 
14 stack.push(currentDay);
15 }
16 
17 return result;
18}

4. Trace Table: temperatures = [73, 74, 75, 71, 69, 72, 76, 73]

Day ($i$)TempStack Before (Indices)While Loop Condition (top_temp < curr)Pops & Result UpdatesStack After
073[]FalseNone[0]
174[0] (73)73 < 74 (True)Pop 0 → res[0] = 1 - 0 = 1[1]
275[1] (74)74 < 75 (True)Pop 1 → res[1] = 2 - 1 = 1[2]
371[2] (75)75 < 71 (False)None[2, 3]
469[2, 3] (75, 71)71 < 69 (False)None[2, 3, 4]
572[2, 3, 4] (75, 71, 69)69 < 72, then 71 < 72Pop 4 → res[4]=1, Pop 3 → res[3]=2[2, 5]
676[2, 5] (75, 72)72 < 76, then 75 < 76Pop 5 → res[5]=1, Pop 2 → res[2]=4[6]
773[6] (76)76 < 73 (False)None[6, 7]

Final Result: [1, 1, 4, 2, 1, 1, 0, 0]. Every index is pushed and popped at most once: $O(n)$ time!


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What is the time complexity of the Monotonic Stack solution for finding the Next Greater Element for all $n$ items in an array?
Question 2
Why do we store the indices of elements on the stack rather than their raw values in problems like Daily Temperatures?
Question 3
What property is maintained by a Monotonically Decreasing Stack?
Question 4
Which advanced algorithmic problem is famously solved in $O(n)$ linear time using a monotonic increasing stack?
Question 5
What is the auxiliary space complexity of a Monotonic Stack for an array of size $n$?

Next Lesson

Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Stacks: LIFO Operations, Array/List Implementations & Bracket MatchingQueues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext