Monotonic Stack Implementation in Go
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 Go as in every other language.
- ✓Nothing to import: a slice is the stack. Push is s = append(s, x) and pop is s = s[:len(s)-1], and both are amortised O(1).
- ✓Preallocate with make([]int, 0, n) since the stack is bounded by the input length, and read the top as s[len(s)-1] guarded by len(s) > 0.
- ✓The Go trap: Truncating with s = s[:len(s)-1] does not clear the popped slot. The backing array still holds the value, so a stack of pointers or of structs containing pointers keeps those objects reachable and unreclaimable until the slice itself is garbage.
- ✓append grows the backing array by doubling below 256 elements and by roughly a quarter above it, so a preallocated slice avoids the copies entirely.
What Monotonic Stack actually is
Monotonic Stack in Go: what you actually reach for
Go implementation
package monotonic
// DailyTemperatures returns, for each day, how many days until a warmer one.
func DailyTemperatures(temps []int) []int {
answer := make([]int, len(temps))
// Bounded by n: preallocate so append never reallocates in the loop.
stack := make([]int, 0, len(temps))
for i, t := range temps {
// Indexing an empty slice panics, so the length guard is required.
for len(stack) > 0 && temps[stack[len(stack)-1]] < t {
j := stack[len(stack)-1]
stack = stack[:len(stack)-1]
answer[j] = i - j
}
stack = append(stack, i)
}
return answer
}
// PopPointer shows the clearing step that matters when the stack holds
// pointers: re-slicing alone leaves the popped element reachable through
// the backing array, so it is never collected.
func PopPointer(stack []*Node) (*Node, []*Node) {
n := len(stack)
if n == 0 {
return nil, stack
}
top := stack[n-1]
stack[n-1] = nil // release the reference BEFORE truncating
return top, stack[:n-1]
}
type Node struct{ Value int }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 Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Monotonic Stack?
Nothing to import: a slice is the stack. Push is s = append(s, x) and pop is s = s[:len(s)-1], and both are amortised O(1).
What is the most common Go mistake when implementing Monotonic Stack?
Truncating with s = s[:len(s)-1] does not clear the popped slot. The backing array still holds the value, so a stack of pointers or of structs containing pointers keeps those objects reachable and unreclaimable until the slice itself is garbage. For a stack of ints this is harmless; for a stack of large structs or pointers it is a genuine leak, and the fix is to zero the slot before truncating. A second trap: passing a slice to a function that appends may or may not affect the caller depending on whether the append reallocated, which makes push helpers that take the slice by value quietly unreliable.
How does Monotonic Stack actually perform in Go?
append grows the backing array by doubling below 256 elements and by roughly a quarter above it, so a preallocated slice avoids the copies entirely. Slices of int are contiguous and unboxed, and the bounds check in the hot loop is usually eliminated by the compiler once it can prove the index is in range. 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 trialBefore paying for GitHub Copilot, check its student and free-tier options 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.