Moyen 0 résolus 0 % de réussite

Min Stack

Build a stack that reports its smallest element instantly after any push or pop.

Ce que vous allez apprendre

  • Track the minimum alongside each push
  • Answer min queries in constant time
  • Handle pops on an empty stack safely

Problème

Afficher la traduction

A generic Stack<T> works for any type. Here you extend the idea: a stack of integers that can also report its minimum in constant time.

Process the operations in order:

  • push <x>: push x.
  • pop: remove the top value (ignored when the stack is empty).
  • min: report the smallest value currently in the stack, or -1 if it is empty.

Implement min_stack_operations(operations).

Input

operations: The operations.

Output

Return the answers of the min operations, in order.

Contraintes

1 ≤ number of operations ≤ 200,000

0 ≤ x ≤ 10^9

Exemples

Exemple 1
Entrée :
operations = ["push 5", "push 3", "min", "pop", "min"]

Sortie attendue :
expected = [3, 5]
Entrée :
std::vector<std::string> operations = {"push 5", "push 3", "min", "pop", "min"};

Sortie attendue :
std::vector<long long> expected = {3, 5};
Entrée :
string[] operations = new string[] {"push 5", "push 3", "min", "pop", "min"};

Sortie attendue :
long[] expected = new long[] {3, 5};

Explication

With 5 and 3 on the stack the minimum is 3. After popping 3, only 5 is left: [3, 5].

Exemple 2
Entrée :
operations = ["min", "pop", "push 7", "min"]

Sortie attendue :
expected = [-1, 7]
Entrée :
std::vector<std::string> operations = {"min", "pop", "push 7", "min"};

Sortie attendue :
std::vector<long long> expected = {-1, 7};
Entrée :
string[] operations = new string[] {"min", "pop", "push 7", "min"};

Sortie attendue :
long[] expected = new long[] {-1, 7};

Explication

The empty stack reports -1 and the pop is ignored; then the minimum is 7: [-1, 7].

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Store, next to each value, the minimum of the stack at that point.

Indice 2

The current minimum is then simply the top of that second stack.

Indice 3

Ignore pop on an empty stack, and answer -1 for min when it is empty.

Complexité attendue

O(number of operations) time, O(number of operations) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.