This program demonstrates a stack that supports not only push and pop operations but also retrieving the minimum element in constant time. The structure of this specialized stack includes an auxiliary stack that keeps track of the minimum values.

Program Structure

The stack is implemented using two lists:

  • The main stack that holds all the elements.
  • An auxiliary stack that holds the minimums.

Each time an element is added, the program checks if it should update the current minimum. Every time an element is removed, it also updates the minimum by popping from the auxiliary stack if necessary.

Python Code

class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = []

    def push(self, x):
        self.stack.append(x)
        if not self.min_stack or x <= self.min_stack[-1]:
            self.min_stack.append(x)

    def pop(self):
        x = self.stack.pop()
        if x == self.min_stack[-1]:
            self.min_stack.pop()

    def top(self):
        return self.stack[-1]

    def getMin(self):
        return self.min_stack[-1]

# Example Usage
min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print("Minimum element:", min_stack.getMin())  # Returns -3
min_stack.pop()
print("Top element:", min_stack.top())         # Returns 0
print("Minimum element:", min_stack.getMin())  # Returns -2

Explanation of the Code

  • __init__: Initializes two stacks; one for all elements and another for the minimums.
  • push: Adds an element to the main stack and, if it’s smaller than or equal to the current minimum, also pushes it onto the min stack.
  • pop: Removes the top element from the main stack and, if it’s the current minimum, also pops from the min stack.
  • top: Returns the top element of the main stack without removing it.
  • getMin: Returns the current minimum element, which is the top of the min stack.

Usage

This min stack can be used in scenarios where it’s crucial to frequently retrieve the minimum element of a stack efficiently, such as in algorithm optimizations, data stream processing, and more.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)