diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_52_min_stack.py b/src/my_project/interviews/top_150_questions_round_22/ex_52_min_stack.py new file mode 100644 index 00000000..c00d581c --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_52_min_stack.py @@ -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] \ No newline at end of file diff --git a/src/my_project/interviews_typescript/top_150_questions_round_1/test_52_min_stack_round_22.ts b/src/my_project/interviews_typescript/top_150_questions_round_1/test_52_min_stack_round_22.ts new file mode 100644 index 00000000..e8fe8df7 --- /dev/null +++ b/src/my_project/interviews_typescript/top_150_questions_round_1/test_52_min_stack_round_22.ts @@ -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] + } +} \ No newline at end of file diff --git a/tests/test_150_questions_round_22/test_52_min_stack_round_22.py b/tests/test_150_questions_round_22/test_52_min_stack_round_22.py new file mode 100644 index 00000000..baed0d82 --- /dev/null +++ b/tests/test_150_questions_round_22/test_52_min_stack_round_22.py @@ -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) + + \ No newline at end of file