Skip to content
Related Articles

Related Articles

What is the time efficiency of the push(), pop(), isEmpty() and peek() operations of Stacks?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 13 Jul, 2022

Stack is a linear data structure that follows the LIFO (last in first out) order i.e., the data are entered from one end and while they are removed, they will be removed from the same end. 

The few most performed operations in a stack are:

  1. push()
  2. pop()
  3. isEmpty()
  4. peek()

Now let us check the time efficiency of the operations:

1. push():

This function is called to insert a new element into the stack.

Syntax:

stack.push(value)

Time Complexity: O(1)

Reason: When the function is called a new element is entered into the stack and the top is changed to point to the newly entered element. Also, a link between the new and the old top pointer is made. These are constant time operations.

2. pull()

This function is called to remove the topmost element of the stack.

Syntax:

stack.pop() 

Time Complexity: O(1)

Reason: In this operation, the top element is removed and the pointer that was pointing to the topmost element now points to the one just below it. The operations performed in this case are all performed in constant time. 

3. isEmpty():

This function is called to check if the stack is empty or not.

Syntax:

stack.isEmpty() 

Time Complexity: O(1)

4. peek():

This function is called to get the value of the topmost element of the stack.

Syntax:

stack.peek()

Time Complexity: O(1)

Reason: This function only accesses the pointer pointing to the topmost element and gets the value stored there.

For more details, please refer:
Design and Analysis of Algorithms.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!