Implement stack from array
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-12-18
Problem Statement
Design and implement a stack data structure using an array-based approach that supports basic stack operations with proper error handling and extensibility.
Functional Requirements (FR)
Push Operation
•Add an element to the top of the stack.
•If the stack is full, handle overflow condition.
Pop Operation
•Remove and return the top element of the stack.
•If the stack is empty, handle underflow condition.
Peek / Top Operation
•Return the element at the top of the stack without removing it.
isEmpty Operation
•Check if the stack has no elements.
isFull Operation
•Check if the stack has reached its maximum capacity.
Size Operation
•Return the current number of elements in the stack.
Non-Functional Requirements (NFR)
•Performance → All operations should run in O(1) time.
•Memory Efficiency → Use a fixed-size array (or optionally a dynamic resizable array).
•Reliability → Proper error handling for overflow and underflow.
Core Entities & Attributes
Stack
•int[] arr → underlying array to store elements.
•int top → index of the top element.
•int capacity → maximum stack size.
Core Operations (APIs)
•push(int element)
•int pop()
•int peek()
•boolean isEmpty()
•boolean isFull()
•int size()
Design Goals
•Encapsulation → Internal array and index tracking should be hidden from users.
•Reusability → Can be extended for generic stack (e.g., Stack<T> in Java).
•Trade-offs →
•Fixed-size array → fast, but limited capacity.
•Dynamic resizing array → flexible, but resizing costs extra time occasionally.