STACK12 - Editorial

Problem Link - Peek, isEmpty, isFull

Problem Statement:

The peek, isEmpty, and isFull are some other functions used in stacks.

  1. peek - This function allows you to look at the element at the top of the stack. It’s a way to inspect the next item that would be removed if a pop operation were to be performed.

    • For a stack: Peek would return the last item added (since stacks follow Last In, First Out order).
  2. isEmpty - This function checks whether a data structure (like a stack, queue, list, etc.) contains any elements or not.

    • If the data structure contains no elements, isEmpty returns true.

    • If there is at least one element in the data structure, isEmpty returns false.

  3. isFull - This function is typically relevant for a fixed size stack. It allows you to determine if the data structure has reached its maximum capacity.

Approach:

The key idea is to introduce helper functions that allow for better interaction with the stack, such as viewing the top element without removing it, checking if the stack is empty, and determining if the stack is full.

  1. peek Operation:

    • If the stack is not empty (top >= 0), we return and display the value at the top of the stack.
    • If the stack is empty (top == -1), we print an error message indicating that no elements can be “peeked” at.
  2. isEmpty Operation:

    • This function simply checks if the value of top is -1. If it is, the stack is empty, and it returns 1 (true). Otherwise, it returns 0 (false), meaning the stack has elements.
  3. isFull Operation:

    • This function checks if the stack is full by comparing top to MAX_SIZE. If top has reached MAX_SIZE, the stack is full and returns 1 (true), otherwise it returns 0 (false).

Time Complexity:

  • peek, isEmpty, and isFull all have a time complexity of O(1) since they perform a constant amount of work by checking the value of top.

Space Complexity:

  • The space complexity remains O(MAX_SIZE), which is the space used by the array a to store the elements of the stack. No additional space is required for these operations.