Designing stacks for getMin functionality

Posted by kooza on Sat, 05 Oct 2019 01:12:12 +0200

Title Description

Implement a special function stack, on the basis of realizing the basic functions of the stack, and then realize the operation of returning the smallest element in the stack.

Input description

The first line enters an integer N, representing the total number of operations performed on the stack.

The following N lines enter a string S for each line, indicating the type of operation.

If S is "push", then there is an integer X that means pushing the integer X into the stack.

If S is "pop", it means pop-up at the top of the stack.

If S is "getMin", it means asking what the smallest element in the current stack is.

Output description

For each getMin operation, the output line represents the minimum element in the current stack.

code implementation

N = int(input().strip())
stack = []
min_express = []
for i in range(N):
    temp = input().split()
    flag = temp[0]
    if flag == 'push':
        num = int(temp[1])
        stack.append(num)
        if len(min_express) == 0:
            min_express.append(num)
        else:
            if num < min_express[-1]:
                min_express.append(num)
            else:
                min_express.append(min_express[-1])
        continue
    if flag == 'pop':
        stack.pop()
        min_express.pop()
        continue
    if flag == 'getMin':
        print(min_express[-1])
        continue

From the comments, you can see a regular code implementation, which is shown below:

import sys 
 
class GetMinStack(object):
    def __init__(self):
        self.stackData=[]
        self.stackMin=[]
    def push(self,num):
        self.stackData.append(num)
        if len(self.stackMin)==0 or num<=self.getMin():
            self.stackMin.append(num)
        else:
            self.stackMin.append(self.getMin())
    def pop(self):
        if len(self.stackData)==0:
            raise Exception("stack is empty")
        self.stackMin.pop()
        return self.stackData.pop()
    def getMin(self):
        if len(self.stackMin)==0:
            raise Exception("stack is empty")
        return self.stackMin[-1]
 
N = int(sys.stdin.readline().strip())
getMinStack = GetMinStack()
for i in range(N):
    line = sys.stdin.readline().strip()
    words = line.split()
    if words[0] == "push":
        getMinStack.push(int(words[1]))
    elif words[0] == "pop":
        getMinStack.pop()
    else:
        print(getMinStack.getMin())