⌘K
Flycodx

Minimum Stack

Minimum Stack

MediumStacks100% accepted

Design a special stack data structure that supports the following operations, all in O(1) time: - PUSH x — push integer x onto the stack - POP — remove the top element from the stack - MIN — return (and print) the current minimum element in the stack

Input format — only if your code reads from stdin

Input format: - First line: integer q (number of operations) - Next q lines: each line is one of: "PUSH x", "POP", or "MIN" Output: for every MIN operation, print the current minimum on its own line. Note: POP and MIN will never be called on an empty stack.

Approach

Maintain two stacks in parallel: the main stack and a min-stack. On PUSH: push to main stack; push to min-stack if new value ≤ current min-stack top (or min-stack is empty). On POP: pop from main; also pop from min-stack if that value equals the main stack's popped value.

Input

6 PUSH 5 PUSH 3 PUSH 7 MIN POP MIN

Output

3 3
  • •1 ≤ q ≤ 10^4, -10^9 ≤ x ≤ 10^9
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3