Monotonic Stack Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Monotonic Stack runs in O(n) time and O(n) space, in C# as in every other language.
- ✓System.Collections.Generic.Stack<T> with Push, Pop and Peek, plus TryPop and TryPeek added in .NET Core 2.0, which return a bool and hand the value back through an out parameter instead of throwing.
- ✓Use while (stack.TryPeek(out var top) && heights[top] >= h). It tests emptiness and reads the top in one call, avoiding both the exception path and the double lookup of checking Count and then calling Peek.
- ✓The C# trap: Pop and Peek throw InvalidOperationException on an empty stack, so the Try forms exist precisely to keep exceptions off the hot path.
- ✓Because .NET generics are reified rather than erased, Stack<int> stores raw 32-bit integers in an int[] with no boxing whatsoever, which is a real advantage over the equivalent Java code.
What Monotonic Stack actually is
Monotonic Stack in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Generic;
public static class MonotonicStack
{
/// <summary>For each day, how many days until a warmer one. O(n).</summary>
public static int[] DailyTemperatures(int[] temps)
{
var answer = new int[temps.Length];
// Reified generics: Stack<int> stores raw ints, no boxing.
var stack = new Stack<int>(temps.Length);
for (int i = 0; i < temps.Length; i++)
{
// TryPeek tests emptiness and reads the top in ONE call.
// Peek() would throw InvalidOperationException when empty.
while (stack.TryPeek(out int top) && temps[top] < temps[i])
{
stack.Pop();
answer[top] = i - top;
}
stack.Push(i);
}
return answer;
}
/// <summary>Largest rectangle in a histogram.</summary>
public static long LargestRectangle(ReadOnlySpan<int> heights)
{
var stack = new Stack<int>(heights.Length + 1);
long best = 0;
for (int i = 0; i <= heights.Length; i++)
{
int h = i == heights.Length ? 0 : heights[i];
while (stack.TryPeek(out int top) && heights[top] >= h)
{
stack.Pop();
long height = heights[top];
long left = stack.TryPeek(out int below) ? below : -1;
best = Math.Max(best, height * (i - left - 1));
}
stack.Push(i);
}
return best;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Monotonic Stack?
System.Collections.Generic.Stack<T> with Push, Pop and Peek, plus TryPop and TryPeek added in .NET Core 2.0, which return a bool and hand the value back through an out parameter instead of throwing.
What is the most common C# mistake when implementing Monotonic Stack?
Pop and Peek throw InvalidOperationException on an empty stack, so the Try forms exist precisely to keep exceptions off the hot path. Two structural surprises follow from the design: Stack<T> enumerates in pop order, top first, which is the reverse of List<T> and catches people who serialise it for debugging; and it exposes no indexer at all, so there is no way to look one below the top without popping, which is why algorithms needing the second element usually keep a List<T> instead.
How does Monotonic Stack actually perform in C#?
Because .NET generics are reified rather than erased, Stack<int> stores raw 32-bit integers in an int[] with no boxing whatsoever, which is a real advantage over the equivalent Java code. Constructing with new Stack<int>(n) presizes the backing array and removes the doubling copies. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.