Problem Link - Push and Pop
Problem Statement:
We are implementing a Stack using an array. The stack will have a maximum capacity defined by MAX_SIZE
. The stack will support two operations:
- Push: To add an element to the stack.
- Pop: To remove the top element from the stack.
We also use a variable top
to keep track of the current top of the stack. Initially, top
is set to -1
since the stack is empty.
Approach:
The key idea is to use an array to store elements in a stack-like structure, where the last element added is the first element removed (LIFO - Last In, First Out).
-
Push Operation:
- We check if the stack is full by comparing
top
toMAX_SIZE - 1
. - If it’s not full, we increment
top
and add the new element at the newtop
position in the array. - If it’s full, we print a message indicating that no more elements can be added.
- We check if the stack is full by comparing
-
Pop Operation:
- We check if the stack is empty by verifying if
top
is-1
. - If it’s not empty, we remove the element from the current
top
position, print it, and decrementtop
. - If the stack is empty, we print an error message indicating that there are no elements to pop.
- We check if the stack is empty by verifying if
Time Complexity:
- Push and Pop operations both take O(1) time since we only access and modify the array at specific positions without any loops or additional computations.
Space Complexity:
- The space complexity is O(MAX_SIZE), which is the space used by the array
a
to store the elements of the stack. Other variables such astop
use constant space.