What is the time complexity of a push operation in a Stack?

Java MCQ: What is the time complexity of a push operation in a Stack?

A) O(n)
B) O(n log n)
C) O(1)
D) O(n²)

Answer:

C) O(1)

Explanation:

The time complexity of a push operation in a stack is O(1), which means that the operation is performed in constant time, regardless of the number of elements in the stack. This efficiency is a key feature of the stack data structure, making it ideal for scenarios where fast insertion and removal of elements are required.

When you perform a push operation, you simply add an element to the top of the stack. Since there’s no need to traverse or shift other elements, the operation takes the same amount of time regardless of the stack’s size. This O(1) time complexity ensures that stacks can handle a high frequency of push operations efficiently, even in applications with large amounts of data.

For example, consider the following code where multiple elements are pushed onto a stack:


import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10); // O(1) operation
        stack.push(20); // O(1) operation
        stack.push(30); // O(1) operation
        System.out.println(stack); // Outputs: [10, 20, 30]
    }
}

In this example, each push operation is executed in constant time, demonstrating the O(1) complexity. The efficiency of push operations in a stack is one of the reasons why stacks are commonly used in scenarios like recursion, function call management, and expression evaluation, where quick access to the most recently added elements is crucial.

Reference links:

https://www.javaguides.net/p/java-stack-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top