Min Stack

Medium

Min Stack Problem

Problem Statement

Design a min stack that allows the following operations:

  • push(int x)
    : Pushes element
    x
    onto the stack.
  • pop()
    : Removes and returns the top element from the stack. If the stack is empty, it returns
    -1
    .
  • top()
    : Returns the top element from the stack without removing it.
  • getMin()
    : Returns the minimum element in the stack.

Rules and Constraints

  • The
    push
    and
    pop
    operations should take constant time.
  • The
    top
    and
    getMin
    operations should take constant time.
  • The total memory used should be O(n) where n is the number of elements pushed into the stack.

Notes

The min stack should handle the following edge cases:

  • When the stack is empty,
    pop()
    should return
    -1
    .
  • When no elements are pushed into the stack,
    getMin()
    should return a meaningful value (i.e. not a default value or error).
  • When the only element pushed into the stack is popped out, the
    getMin()
    operation should return the same result as when the element was first pushed into the stack.

The min stack should maintain the order in which elements were pushed onto the stack.

Example

Input: {"operations":["push","push","getMin"]} Output: [null,null,-3]

CompaniesGoogle
JavaScript

Login to write code

Solve problems, verify your skills, and earn XP.