Min Stack With Auxiliary Stack
A second stack records each new minimum as it is pushed and pops it back off with the main stack, keeping the current minimum one read away.
Code
package main
import "fmt"
// the auxiliary stack pushes only when a new minimum appears, popping in lockstep with the main stack
type MinStack struct {
stack []int
mins []int
}
func (s *MinStack) Push(v int) {
s.stack = append(s.stack, v)
if len(s.mins) == 0 || v <= s.mins[len(s.mins)-1] {
s.mins = append(s.mins, v)
}
}
func (s *MinStack) Pop() int {
top := s.stack[len(s.stack)-1]
s.stack = s.stack[:len(s.stack)-1]
if top == s.mins[len(s.mins)-1] {
s.mins = s.mins[:len(s.mins)-1]
}
return top
}
func (s *MinStack) Min() int {
return s.mins[len(s.mins)-1]
}
func main() {
s := &MinStack{}
for _, v := range []int{5, 3, 7, 2, 8} {
s.Push(v)
}
fmt.Println("min:", s.Min())
fmt.Println("pop:", s.Pop())
fmt.Println("pop:", s.Pop())
fmt.Println("min:", s.Min())
}Inside the snippet
Structurally, expect the functions Push, Pop, Min and main and nothing else.
Iteration happens inside for _, v := range []int{5, 3, 7, 2, 8} — everything outside it runs once.
Caveats
- All of it is standard-library — paste it in and it runs.
Putting it to use
Entry signature: func (s *MinStack) Push(v int)
Output lines are prefixed (min:, pop:), so each step’s effect shows up clearly in the output.
main sequences Push, Min and Pop; executing the file runs that flow once.
Core lines under the microscope
for _, v := range []int{5, 3, 7, 2, 8} {
s.Push(v)
}
func (s *MinStack) Push(v int) {
s.stack = append(s.stack, v)
if len(s.mins) == 0 || v <= s.mins[len(s.mins)-1] {
s.mins = append(s.mins, v)
}
}
func (s *MinStack) Pop() int {
top := s.stack[len(s.stack)-1]
s.stack = s.stack[:len(s.stack)-1]
if top == s.mins[len(s.mins)-1] {
s.mins = s.mins[:len(s.mins)-1]
}
return top
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Min Stack With Auxiliary Stack print when run?
- The script runs standalone; its 2 labeled outputs include `min:`, `pop:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.