Welcome to my personal website. I use this space to share some of my thoughts and software that I write in my free time. Sometimes I also publish photos. If you want to get in touch please use LinkedIn or Mastodon.
Create a stack implementation that is able to return the minimum element as well as push and pop elements, all in constant time O(1).
I used the builtin heapqlibrary which provides a heap implementation. This works realiably to find the minimum element. When deleting element from the stack structure we don’t know where on the heap the element is stored. Any type of scanning the heap would violate the O(1) requirement. Instead, I chose to store the deleted elements in a dictionary. If the min element should be returned, the tombstones are checked. If the element is marked as deleted, the next item is checked, and so on. I use a list as the actual stack because append and pop perform both in O(1).
Runtime: 157 ms, faster than 12.25% of Python3 online submissions for Min Stack. Memory Usage: 18 MB, less than 60.07% of Python3 online submissions for Min Stack.
About the author
Friedrich Ewald is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.