Минимум на стеке python

Минимум на стеке python

  • Convert Infix expression to Postfix expression
  • Prefix to Infix Conversion
  • Prefix to Postfix Conversion
  • Postfix to Prefix Conversion
  • Postfix to Infix
  • Convert Infix To Prefix Notation
  • Check for Balanced Brackets in an expression (well-formedness)
  • Arithmetic Expression Evaluation
  • Evaluation of Postfix Expression
  • How to Reverse a Stack using Recursion
  • Reverse individual words
  • How to Reverse a String using Stack
  • Reversing a Queue
  • How to create mergeable stack?
  • The Stock Span Problem
  • Next Greater Element (NGE) for every element in given Array
  • Next Greater Frequency Element
  • Maximum product of indexes of next greater on left and right
  • Iterative Tower of Hanoi
  • Sort a stack using a temporary stack
  • Reverse a stack without using extra space in O(n)
  • Delete middle element of a stack
  • Check if a queue can be sorted into another queue using a stack
  • Check if an array is stack sortable
  • Largest Rectangular Area in a Histogram using Stack
  • Find maximum of minimum for every window size in a given array
  • Find index of closing bracket for a given opening bracket in an expression
  • Find maximum difference between nearest left and right smaller elements
  • Delete consecutive same words in a sequence
  • Check mirror in n-ary tree
  • Reverse a number using stack
  • Reversing the first K elements of a Queue
  • The Celebrity Problem
  • Print next greater number of Q queries
  • Iterative Postorder Traversal | Set 2 (Using One Stack)
  • Print ancestors of a given binary tree node without recursion
  • Length of the longest valid substring
  • Expression contains redundant bracket or not
  • Find if an expression has duplicate parenthesis or not
  • Find next Smaller of next Greater in an array
  • Iterative method to find ancestors of a given binary tree
  • Stack Permutations (Check if an array is stack permutation of other)
  • Spaghetti Stack
  • Remove brackets from an algebraic string containing + and – operators
  • Range Queries for Longest Correct Bracket Subsequence Set | 2
  • Convert Infix expression to Postfix expression
  • Prefix to Infix Conversion
  • Prefix to Postfix Conversion
  • Postfix to Prefix Conversion
  • Postfix to Infix
  • Convert Infix To Prefix Notation
  • Check for Balanced Brackets in an expression (well-formedness)
  • Arithmetic Expression Evaluation
  • Evaluation of Postfix Expression
  • How to Reverse a Stack using Recursion
  • Reverse individual words
  • How to Reverse a String using Stack
  • Reversing a Queue
  • How to create mergeable stack?
  • The Stock Span Problem
  • Next Greater Element (NGE) for every element in given Array
  • Next Greater Frequency Element
  • Maximum product of indexes of next greater on left and right
  • Iterative Tower of Hanoi
  • Sort a stack using a temporary stack
  • Reverse a stack without using extra space in O(n)
  • Delete middle element of a stack
  • Check if a queue can be sorted into another queue using a stack
  • Check if an array is stack sortable
  • Largest Rectangular Area in a Histogram using Stack
  • Find maximum of minimum for every window size in a given array
  • Find index of closing bracket for a given opening bracket in an expression
  • Find maximum difference between nearest left and right smaller elements
  • Delete consecutive same words in a sequence
  • Check mirror in n-ary tree
  • Reverse a number using stack
  • Reversing the first K elements of a Queue
  • The Celebrity Problem
  • Print next greater number of Q queries
  • Iterative Postorder Traversal | Set 2 (Using One Stack)
  • Print ancestors of a given binary tree node without recursion
  • Length of the longest valid substring
  • Expression contains redundant bracket or not
  • Find if an expression has duplicate parenthesis or not
  • Find next Smaller of next Greater in an array
  • Iterative method to find ancestors of a given binary tree
  • Stack Permutations (Check if an array is stack permutation of other)
  • Spaghetti Stack
  • Remove brackets from an algebraic string containing + and – operators
  • Range Queries for Longest Correct Bracket Subsequence Set | 2
Читайте также:  Соединение базы данных в java

Источник

155. Min Stack (Python)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

Note

Do not modify the linked list.

Sample I/O

Example 1

Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 

Constraints

Methodology

Push, pop and top are basic stack operations and they are easy to implemented by list. However, the hard part is getMin(). To implement Push, pop and top, we have to keep the original order. To get min we somehow need to create extra space (min_stack) to stor the value in min order. If so, we have to compare the number with others each time when we insert the number into min_stack and this will cost a lot. The better way is to use index and priority level to mark each number in min_stack.

 def __init__(self): """ initialize your data structure here. """ self.stack = [] self.index = -1 self.min_stack = [] self.min_index = -1 self.min_value = float("inf") def push(self, x: int) -> None: if x  self.min_value: self.min_stack.append([x,1]) self.min_value = x self.min_index += 1 elif x == self.min_value: self.min_stack[self.min_index][1]+=1 self.stack.append(x) self.index += 1 def pop(self) -> None: if self.index  0: return value = self.stack.pop() if value == self.min_value: self.min_stack[self.min_index][1] -= 1 if self.min_stack[self.min_index][1] == 0: self.min_stack.pop() self.min_index -= 1 if self.min_index != -1: self.min_value = self.min_stack[self.min_index][0] else: self.min_value = float("inf") if self.min_stack == -1: return self.index -= 1 def top(self) -> int: if self.index  0: return return self.stack[self.index] def getMin(self) -> int: return self.min_value 

BigO

No need to iterate the stack or list, all operations push, pop, top and getMin are O(1)

Источник

Python implementation of stack to return minimum in O(1) time

I have written a stack in Python that is required to push, pop and return the minimum of the stack in \$O(1)\$ time.

#!python3 class Stack(): def __init__(self): self.items = [] self.min = None def push(self, item): self.items.append(item) self.minimum() def pop(self): if self.isEmpty(): raise ValueError('Empty stack') else: return self.items.pop() def minimum(self): if self.min is None: self.min = self.peek() else: if self.peek() < self.min: self.min = self.peek() def getMinimum(self): return self.min def peek(self): try: return self.items[-1] except IndexError as e: print(e) def size(self): return len(self.items) def isEmpty(self): return self.size() == 0 stack = Stack() nums = [6,4,8,9,1,5,2,3] for i in nums: stack.push(i) print(stack.getMinimum()) 

What I have tried to do is, compare the current minimum with each new addition to the stack so that the

3 Answers 3

You can correctly implement the stack with minimum query by maintaining a second array that holds current minimum on its top. When you push the very first element, you append it to both the arrays. Next, when you push the subsequent element \$e\$, you append it to the actual stack array as is, but you push \$\min \< e, e' \>\$ to the minimum stack, where \$e'\$ is the top element of the minimum stack. Popping is trivial: just pop both the actual element array and the minimum array. All in all, it might look like this:

class Stack(): def __init__(self): self.element_stack = [] self.min_element_stack = [] def push(self, item): if self.size() == 0: self.min_element_stack.append(item) else: self.min_element_stack.append(min(self.min_element_stack[self.size() - 1], item)) self.element_stack.append(item) def pop(self): if self.is_empty(): raise ValueError('Empty stack') self.min_element_stack.pop() return self.element_stack.pop() def minimum(self): if self.is_empty(): raise ValueError('Empty stack') return self.min_element_stack[self.size() - 1] def is_empty(self): return self.size() == 0 def size(self): return len(self.element_stack) def main(): stack = Stack() stack.push(3) print(stack.minimum()) stack.push(5) print(stack.minimum()) stack.push(1) print(stack.minimum()) stack.pop() print(stack.minimum()) if __name__ == "__main__": main() 

Источник

Как и зачем делать очередь на двух стеках

Данный пост написан для новичков в олимпиадном программировании и начинающих разработчиков, готовящихся к прохождению алгоритмических интервью. В конце бонусная задачка. Если заинтересовал, прошу под кат 🙂

Для начала вспомним основы:

Стек

Стек реализует принцип LIFO (англ. last in — first out, «последним пришёл — первым вышел»).

Стек имеет две основные операции:

Очередь

Очередь — это структура данных с доступом к элементам FIFO (англ. First In, First Out – «первым пришёл — первым ушёл»)

Очередь имеет два основных метода в своем интерфейсе:

Обычно рассматривают два базовых подхода к реализации очереди:

Почему стек круче, чем очередь

Представим себе, что наша структура данных должна поддерживать следующий набор операций:

  • Поддержка минимума (min)
  • Поддержка максимума (max)
  • Поддержка gcd (англ. greatest common divisor — наибольший общий делитель)
  • Поддержка lcm (англ. least common multiple — наименьшее общее кратное)

Для стека можно очень просто поддерживать любую из приведенных операций: достаточно хранить на его вершине пару:

, где второй элемент пары — результат операции, примененной ко всем элементам стека.

Ниже пример реализации стека с поддержкой минимума на Python:

class Stack: def __init__(self): self.stack = [] def __bool__(self): return bool(self.stack) def push(self, elem): if self.stack: self.stack.append((elem, min(elem, self.stack[-1][1]))) else: self.stack.append((elem, elem)) def pop(self): return self.stack.pop()[0] def get_min(self): if not self.stack: return math.inf return self.stack[-1][1] 

А теперь подумайте, как проделать тот же фокус с очередью? Если пробовать с классической очередью, организованной на массиве, вряд ли что-то получится. Это связано с тем, что операция минимум не имеет обратную операцию (как операция сложения имеет операцию вычитания, например). Как вы могли догадаться, далее я расскажу о не совсем классической реализации очереди на двух стеках.

Очередь на двух стеках

Главное условие, которое должно быть выполнено — все операции должны выполняться за амортизированное O(1).

Возьмем два стека: s1 и s2.

Операцию push будем всегда делать в стек s1.

Операция pop будет устроена так: если стек s2 пустой, перекладываем все элементы из s1 в s2 последовательными вызовами pop и push. Теперь в стеке s2 лежат элементы в обратном порядке (самый верхний элемент — это самый первый положенный элемент в нашу очередь).

Если s2 не пуст, тупо достаем элементы из него. Как только s2 окажется снова пустым повторяем ту же операцию.

class Queue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def push(self, elem): self.s1.push(elem) def pop(self): if not self.s2: while self.s1: self.s2.push(self.s1.pop()) return self.s2.pop() def get_min(self): return min(self.s1.get_min(), self.s2.get_min()) 

Время работы

Операция push: Мы тупо кладем элемент в стек s1. Время работы O(1).

Операция pop: Для каждого элемента мы делаем не более одного перекладывания из стека в стек, следовательно амортизированное время работы составит O(1).

Операция get_min: Для стеков s1 и s2 известны минимумы, поэтому мы просто берем минимум из минимумов. Время работы O(1).

Бонусная задачка

Заключение

Спасибо, что дочитали до конца!

Если вас заинтересовала тема, можете почитать как сделать персистентную очередь на двух стеках здесь, либо дождаться выхода следующего моего топика.

Пишите в комментариях какие задачи на двух стеках вам приходилось решать на интервью или контестах.

Источник

Оцените статью