KatInterview

Stack Simulator with Constant-Time Minimum Queries

Stacks & QueuesAuto-graded · 17 test cases
EasyAuto-gradedStacks & Queuesstackdesignsimulation

Last updated

Simulate a sequence of stack commands and answer minimum queries in constant time by tracking the running minimum alongside each element.

You are asked to simulate a special stack of integers that, besides the usual operations, can report its smallest element immediately.

The stack supports four commands:

  • "push": place the given integer on top of the stack.
  • "pop": remove the element on top of the stack.
  • "top": report the element currently on top, without removing it.
  • "getMin": report the smallest value currently in the stack.

You receive two lists of equal length. operations[i] is the name of the i-th command, and arguments[i] is the list of arguments for that command. For "push", arguments[i] holds exactly one integer, the value to push. For all other commands, arguments[i] is an empty list.

Process the commands in order, starting from an empty stack, and return a list results of the same length as operations:

  • For "push" and "pop", results[i] is None.
  • For "top", results[i] is the value on top of the stack.
  • For "getMin", results[i] is the minimum value among all elements currently in the stack.

Duplicate values are allowed. After a pop, the minimum must reflect only the elements still in the stack. Every "pop", "top" and "getMin" is issued on a non-empty stack, so you never need to handle an empty-stack error.

Each command should run in O(1) time.

Constraints

  • 1 <= len(operations) == len(arguments) <= 3 * 10^4
  • Each operation is one of "push", "pop", "top", "getMin".
  • Pushed values fit in a 32-bit signed integer.
  • pop, top and getMin are never called on an empty stack.

Examples

Example 1

Input: run_min_stack(['push', 'push', 'push', 'getMin', 'pop', 'top', 'getMin'], [[2], [0], [3], [], [], [], []])

Output: [None, None, None, 0, None, 0, 0]

Example 2

Input: run_min_stack(['push', 'push', 'getMin', 'pop', 'getMin', 'top'], [[-2], [0], [], [], [], []])

Output: [None, None, -2, None, -2, -2]

Example 3

Input: run_min_stack(['push', 'push', 'push', 'getMin', 'pop', 'getMin', 'pop', 'getMin'], [[5], [5], [-1], [], [], [], [], []])

Output: [None, None, None, -1, None, 5, None, 5]

Hints

Hint 1

Think about what the minimum of the stack looks like at the moment each element was pushed. Does that value change while the element is still in the stack?

Hint 2

Keep a second stack of the same height as the first. Each of its entries stores the minimum of everything at or below that position.

Hint 3

When pushing, the new running minimum is min(value, current running minimum), or just the value if the stack is empty. Popping both stacks together restores the previous minimum automatically, and duplicates are handled correctly.