Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created June 13, 2018 16:07
Show Gist options
  • Save lkrych/4279fa848518b7630909b3cd04acf502 to your computer and use it in GitHub Desktop.
Save lkrych/4279fa848518b7630909b3cd04acf502 to your computer and use it in GitHub Desktop.
A more space-efficient implementation of stack with minimum
type stackWithMin struct {
data []int
minStack stack //utilizes the stack implementation we defined above!
}
func (s *stackWithMin) pop() int {
popped := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
if popped == s.min() { //if you've popped the min, move it off the minStack!
s.minStack.pop()
}
return popped
}
func (s *stackWithMin) push(item int) {
s.data = append(s.data, item)
if item <= s.min() { //if the incoming item is less than the current min
s.minStack.push(item)
}
}
func (s *stackWithMin) min() int {
if s.minStack.isEmpty() {
return 100000000000000000 //really large number
}
return s.minStack.peek()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment