보통 0명 해결 정답률 0%

Min Stack

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

배우게 될 내용

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

문제

번역본 보기

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.

제약 조건

1 ≤ number of operations ≤ 200,000

0 ≤ x ≤ 10^9

예시

예시 1
입력:
operations = ["push 5", "push 3", "min", "pop", "min"]

예상 출력:
expected = [3, 5]
입력:
std::vector<std::string> operations = {"push 5", "push 3", "min", "pop", "min"};

예상 출력:
std::vector<long long> expected = {3, 5};
입력:
string[] operations = new string[] {"push 5", "push 3", "min", "pop", "min"};

예상 출력:
long[] expected = new long[] {3, 5};

설명

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

예시 2
입력:
operations = ["min", "pop", "push 7", "min"]

예상 출력:
expected = [-1, 7]
입력:
std::vector<std::string> operations = {"min", "pop", "push 7", "min"};

예상 출력:
std::vector<long long> expected = {-1, 7};
입력:
string[] operations = new string[] {"min", "pop", "push 7", "min"};

예상 출력:
long[] expected = new long[] {-1, 7};

설명

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

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

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

힌트 2

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

힌트 3

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

예상 복잡도

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

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.