Skip to content

Instantly share code, notes, and snippets.

@Warkanlock
Last active November 27, 2025 17:24
Show Gist options
  • Select an option

  • Save Warkanlock/58a2e322283407b90d630919096af74b to your computer and use it in GitHub Desktop.

Select an option

Save Warkanlock/58a2e322283407b90d630919096af74b to your computer and use it in GitHub Desktop.

Implement a stack that supports these operations in O(1) time each:

Operations

  • push(x)
  • pop()
  • top() -> x
  • getMin() -> min

Rules / Constraints:

  • pop() and top() should handle empty stack (either throw or return null, but be consistent).
  • Duplicates exist.
  • Negative values exist.
  • Must be O(1) time, O(n) space.

Example

push(5)
push(2)
push(2)
getMin() -> 2
pop()     // pops 2
getMin() -> 2
pop()     // pops 2
getMin() -> 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment