Skip to content
Related Articles

Related Articles

Time and Space Complexity analysis of Stack operations

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 05 Sep, 2022
View Discussion
Improve Article
Save Article

What is Stack?

Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order. A stack can be implemented using Arrays or Linked Lists.

Complexity analysis of different stack operations:

1) push():

This operation pushes an element on top of the stack and the top pointer points to the newly pushed element. It takes one parameter and pushes it onto the stack.

Below is the implementation of push() using Array :

C++




#include <bits/dtc++.h>
using namespace std;
 
class Stack {
public:
    int stack[10];
    int MAX = 10;
    int top;
 
    Stack() { top = -1; }
 
    void push(int val)
    {
        // If top is pointing to
        // maximum size of stack
        if (top >= MAX - 1) {
 
            // Sstack is full
            cout << "Stack Overflow\n";
            return;
        }
 
        // Point top to new top
        top++;
 
        // Insert new element at top of stack
        stack[top] = val;
        cout << val
             << " pushed into stack successfully !\n";
    }
};
 
int main()
{
    Stack st;
    st.push(1);
    st.push(2);
    return 0;
}

Java




// Java code to push element on top of stack
 
import java.io.*;
 
class GFG {
 
    static class Stack {
        int stack[] = new int[10];
        int MAX = 10;
        int top;
 
        void stack() { top = -1; }
 
        void push(int val)
        {
            // If top is pointing to maximum size of stack
            if (top >= MAX - 1) {
                // Stack is full
                System.out.println("Stack Overflow");
                return;
            }
 
            // Point top to new top
            top++;
 
            // Insert new element at top of stack
            stack[top] = val;
            System.out.println(
                val + " pushed into stack successfully !");
        }
    }
 
    public static void main(String[] args)
    {
        Stack st = new Stack();
        st.push(1);
        st.push(2);
    }
}
 
// This code is contributed by lokeshmvs21.

Output

1 pushed into stack successfully !
2 pushed into stack successfully !

Complexity Analysis:

  • Time Complexity: O(1),  In the push function a single element is inserted at the last position. This takes a single memory allocation operation which is done in constant time.
  • Auxiliary Space: O(1), As no extra space is being used.

Below is the implementation of push() using Linked List :

C++




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};
 
class Stack {
public:
    Node* top;
 
    Stack() { top = NULL; }
 
    void push(int val)
    {
        // Create new node temp and
        // allocate memory in heap
        Node* temp = new Node(val);
 
        // If stack is empty
        if (!top) {
            top = temp;
            cout << val
                 << " pushed into stack successfully !\n";
            return;
        }
 
        temp->next = top;
        top = temp;
        cout << val
             << " pushed into stack successfully !\n";
    }
};
 
int main()
{
    Stack st;
    st.push(1);
    st.push(2);
    return 0;
}

Output

1 pushed into stack successfully !
2 pushed into stack successfully !

Complexity Analysis:

  • Time Complexity: O(1), Only a new node is created and the pointer of the last node is updated. This includes only memory allocation operations. Hence it can be said that insertion is done in constant time.
  • Auxiliary Space: O(1), No extra space is used.

2) pop():

This operation removes the topmost element in the stack and returns an error if the stack is already empty.

Below is the implementation of pop() using Array:

C++




#include <bits/stdc++.h>
using namespace std;
 
class Stack {
public:
    int stack[10];
    int MAX = 10;
    int top;
 
    Stack() { top = -1; }
 
    void push(int val)
    {
        // If top is pointing to maximum size of stack
        if (top >= MAX - 1) {
 
            // Stack is full
            cout << "Stack Overflow\n";
            return;
        }
 
        // Point top to new top
        top++;
 
        // Insert new element at top of stack
        stack[top] = val;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    void pop()
    {
        // Stack is already empty
        if (top < 0) {
            cout << "Stack Underflow";
        }
        else {
            // Removing top of stack
            int x = stack[top--];
            cout << "Element popped from stack : " << x
                 << "\n";
        }
    }
};
 
int main()
{
    Stack st;
    st.push(1);
 
    st.pop();
    st.pop();
    return 0;
}

Output

1 pushed into stack successfully !
Element popped from stack : 1
Stack Underflow

Complexity Analysis:

  • Time Complexity: O(1), In array implementation, only an arithmetic operation is performed i.e., the top pointer is decremented by 1. This is a constant time function.
  • Auxiliary Space: O(1), No extra space is utilized for deleting an element from the stack.

Below is the implementation of pop() using Linked List :

C++




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};
 
class Stack {
public:
    Node* top;
 
    Stack() { top = NULL; }
 
    void push(int val)
    {
        // Create new node temp and allocate memory in heap
        Node* temp = new Node(val);
 
        // If stack is empty
        if (!top) {
            top = temp;
            cout << val
                 << " pushed into stack successfully !\n";
            return;
        }
 
        temp->next = top;
        top = temp;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    void pop()
    {
        Node* temp;
 
        // Check for stack underflow
        if (top == NULL) {
            cout << "Stack Underflow\n"
                 << endl;
            return;
        }
        else {
 
            // Assign top to temp
            temp = top;
 
            cout << "Element popped from stack : "
                 << temp->data << "\n";
 
            // Assign second node to top
            top = top->next;
 
            // This will automatically destroy
            // the link between first node and second node
 
            // Release memory of top node
            // i.e delete the node
            free(temp);
        }
    }
};
 
int main()
{
    Stack st;
    st.push(1);
 
    st.pop();
    st.pop();
    return 0;
}

Output

1 pushed into stack successfully !
Element popped from stack : 1
Stack Underflow

Complexity Analysis:

  • Time Complexity: O(1), Only the first node is deleted and the top pointer is updated. This is a constant time operation.
  • Auxiliary Space: O(1). No extra space is utilized for deleting an element from the stack.

3) peek():

This operation prints the topmost element of the stack.

Below is the Implementation of peek() using Array:

C++




#include <bits/stdc++.h>
using namespace std;
 
class Stack {
public:
    int stack[10];
    int MAX = 10;
    int top;
 
    Stack() { top = -1; }
 
    void push(int val)
    {
        // If top is pointing to maximum size of stack
        if (top >= MAX - 1) {
 
            // Stack is full
            cout << "Stack Overflow\n";
            return;
        }
 
        // Point top to new top
        top++;
 
        // Insert new element at top of stack
        stack[top] = val;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    int peek()
    {
        // Stack is already empty then
        // we can't get peek element
        if (top < 0) {
            cout << "Stack is Empty\n";
            return 0;
        }
        else {
 
            // Retrieving top element from stack
            int x = stack[top];
            return x;
        }
    }
};
 
int main()
{
    Stack st;
    st.push(1);
    st.push(2);
 
    cout << "Peek element of stack : "
         << st.peek() << "\n";
    return 0;
}

Output

1 pushed into stack successfully !
2 pushed into stack successfully !
Peek element of stack : 2

Complexity Analysis:

  • Time Complexity: O(1), Only a memory address is accessed. This is a constant time operation.
  • Auxiliary Space: O(1), No extra space is utilized to access the value.

Below is the implementation of peek() using Linked List :

C++




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};
 
class Stack {
public:
    Node* top;
 
    Stack() { top = NULL; }
 
    void push(int val)
    {
        // Create new node temp and
        // allocate memory in heap
        Node* temp = new Node(val);
 
        // If stack is empty
        if (!top) {
            top = temp;
            cout << val
                 << " pushed into stack successfully !\n";
            return;
        }
 
        temp->next = top;
        top = temp;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    bool isEmpty()
    {
        // If top is NULL it means that
        // there are no elements are in stack
        return top == NULL;
    }
 
    int peek()
    {
        // If stack is not empty,
        // return the top element
        if (!isEmpty())
            return top->data;
        else
            cout << "Stack is Empty\n";
        exit(1);
    }
};
 
int main()
{
    Stack st;
    st.push(1);
    cout << "Peek element of stack : "
         << st.peek() << "\n";
    return 0;
}

Output

1 pushed into stack successfully !
Peek element of stack : 1

Complexity Analysis:

  • Time Complexity: O(1). In linked list implementation also a single memory address is accessed. It takes constant time.
  • Auxiliary Space: O(1). No extra space is utilized to access the element because only the value in the node at the top pointer is read.

4) isempty():

This operation tells us whether the stack is empty or not.

Below is the implementation of isempty() using Array :

C++




#include <bits/stdc++.h>
using namespace std;
 
class Stack {
public:
    int stack[10];
    int MAX = 10;
    int top;
 
    Stack() { top = -1; }
 
    void push(int val)
    {
        // If top is pointing to
        // maximum size of stack
        if (top >= MAX - 1) {
 
            // Stack is full
            cout << "Stack Overflow\n";
            return;
        }
 
        // Point top to new top
        top++;
 
        // Insert new element at top of stack
        stack[top] = val;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    bool isEmpty()
    {
        // If stack is empty return 1
        return (top < 0);
    }
};
 
int main()
{
    Stack st;
    cout << st.isEmpty();
 
    return 0;
}

Output

1

Complexity Analysis:

  • Time Complexity: O(1), It only performs an arithmetic operation to check if the stack is empty or not.
  • Auxiliary Space: O(1), It requires no extra space.

Below is the implementation of isempty() using Linked List :

C++




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};
 
class Stack {
public:
    Node* top;
 
    Stack() { top = NULL; }
 
    void push(int val)
    {
        // Create new node temp and allocate memory in heap
        Node* temp = new Node(val);
 
        // If stack is empty
        if (!top) {
            top = temp;
            cout << val
                 << " pushed into stack successfully !\n";
            return;
        }
 
        temp->next = top;
        top = temp;
        cout << val
             << " pushed into stack successfully !\n";
    }
 
    bool isEmpty()
    {
        // If top is NULL it means that
        // there are no elements are in stack
        return top == NULL;
    }
};
 
int main()
{
    Stack st;
 
    cout << st.isEmpty();
    return 0;
}

Output

1

Complexity Analysis:

  • Time Complexity: O(1), It checks if the pointer of the top pointer is Null or not. This operation takes constant time.
  • Auxiliary Space: O(1), No extra space is required.

5) size():

This operation returns the current size of the stack.

Below is the implementation of size() using Array:

C++




#include <bits/stdc++.h>
using namespace std;
 
class Stack {
public:
    int stack[10];
    int MAX = 10;
    int top;
 
    Stack() { top = -1; }
 
    void push(int val)
    {
        // If top is pointing to maximum size of stack
        if (top >= MAX - 1) {
 
            // Stack is full
            cout << "Stack Overflow\n";
            return;
        }
 
        // Point top to new top
        top++;
 
        // Insert new element at top of stack
        stack[top] = val;
        cout << val
             << " pushed into stack successfully !\n";
    }
    int size() { return top + 1; }
};
 
int main()
{
    Stack st;
    st.push(1);
    st.push(2);
 
    cout << "The size of the stack is " << st.size()
         << endl;
    return 0;
}

Output

1 pushed into stack successfully !
2 pushed into stack successfully !
The size of the stack is 2

Complexity Analysis:

  • Time Complexity: O(1), because this operation just performs a basic arithmetic operation.
  • Auxiliary Space: O(1) NO extra space is required to calculate the value of the top pointer.

Below is the implementation of size() using Linked List:

C++




#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
 
    Node(int val)
    {
        data = val;
        next = NULL;
    }
};
 
class Stack {
public:
    Node* top;
    Node* head;
    int sizeOfStack;
    Stack()
    {
        head = NULL;
        top = NULL;
        sizeOfStack = 0;
    }
 
    void push(int val)
    {
        // Create new node temp and
        // allocate memory in heap
        Node* temp = new Node(val);
        sizeOfStack += 1;
 
        // If stack is empty
        if (!top) {
            top = temp;
            return;
        }
 
        temp->next = top;
        top = temp;
    }
 
    int size() { return sizeOfStack; }
};
 
int main()
{
    Stack st;
    st.push(1);
    st.push(3);
    st.push(4);
 
    cout << "Size of stack : " << st.size();
    return 0;
}

Output

Size of stack : 3

Complexity Analysis:

  • Time Complexity: O(1), because the size is calculated and updated every time a push or pop operation is performed and is just returned in this function.
  • Auxiliary Space: O(1), NO extra space is required to calculate the size of the stack.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!