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.

GoData Integrity

Code

gosnippet
40 lines
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

FAQ

What does Min Stack With Auxiliary Stack print when run?
The script runs standalone; its 2 labeled outputs include `min:`, `pop:`.