STACK11 - Editorial

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).

  1. Push Operation:

    • We check if the stack is full by comparing top to MAX_SIZE - 1.
    • If it’s not full, we increment top and add the new element at the new top position in the array.
    • If it’s full, we print a message indicating that no more elements can be added.
  2. 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 decrement top.
    • If the stack is empty, we print an error message indicating that there are no elements to pop.

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 as top use constant space.