Stack with findMin feature

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-02-23

Problem Statement

Design and implement a custom stack data structure that, in addition to the usual stack operations (push, pop, peek), supports retrieving the minimum element in constant time (findMin).


Functional Requirements (FR)


Push Operation


•Insert an element onto the stack.


Pop Operation


•Remove and return the top element from the stack.
•Handle empty stack case.


Peek Operation


•Return the top element without removing it.


Find Minimum


•Return the minimum element in the stack in O(1) time.


Error Handling


•pop, peek, and findMin should handle empty stack gracefully.


Non-Functional Requirements (NFR)


•Time Complexity: All operations (push, pop, peek, findMin) should run in O(1).
•Space Complexity: Should not use excessive extra memory beyond the stack itself.
•Extensibility: Should support generic types if needed (integers, doubles, etc.).


Core Entities & Attributes


Stack

•Attributes: elements[], minElements[] (auxiliary stack to track minimums), top.
•Operations: push(x), pop(), peek(), findMin().


Example Use Case


1.Push(5) → min = 5.
2.Push(3) → min = 3.
3.Push(7) → min = 3.
4.Push(2) → min = 2.
5.findMin() → 2.
6.Pop() → removes 2 → new min = 3.
7.findMin() → 3.


Evaluation Criteria


•Clean class design with separation of concerns.
•Correct handling of minimum tracking during push/pop.
•Edge cases (empty stack).
•O(1) performance for all operations.


Solution

Comments