Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class MinStack:
def __init__(self):
self.A = []
self.M = []

def push(self, x):
self.A.append(x)
self.M.append(x if not self.M else min(x, self.M[-1]))

def pop(self):
self.A.pop()
self.M.pop()

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

def getMin(self):
return self.M[-1]
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class MinStack {

private stack: number[]
private minStack: number[]

constructor() {
this.stack = [];
this.minStack = [];

}

push(val: number): void {
this.stack.push(val)
if (this.minStack.length === 0){
this.minStack.push(val)
}else{
this.minStack.push(Math.min(val, this.minStack[this.minStack.length - 1]))
}
}

pop(): void {
this.stack.pop()
this.minStack.pop()
}

top(): number {
return this.stack[this.stack.length - 1]
}

getMin(): number {
return this.minStack[this.minStack.length - 1]
}
}
36 changes: 36 additions & 0 deletions tests/test_150_questions_round_22/test_52_min_stack_round_22.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_52_min_stack import MinStack

class MinStackTestCase(unittest.TestCase):

def test_first_pattern(self):
commands = ["MinStack","push","push","push","getMin",
"pop","top","getMin"]
args = [[],[-2],[0],[-3],[],[],[],[]]

expected_output = [None,None,None,None,-3,None,0,-2]

min_stack = None
actual_output = []

for i, command in enumerate(commands):
if command == "MinStack":
min_stack = MinStack()
actual_output.append(None)
elif command == "push":
min_stack.push(args[i][0])
actual_output.append(None)
elif command == "pop":
min_stack.pop()
actual_output.append(None)
elif command == "top":
result = min_stack.top()
actual_output.append(result)
elif command == "getMin":
result = min_stack.getMin()
actual_output.append(result)

self.assertEqual(actual_output, expected_output)