Junior — Middle
What is the time complexity of adding an element to a stack?
sobes.tech AI
Answer from AI
The time complexity of adding an element to a stack is usually O(1) — constant time. This is because a stack is implemented as a data structure with access only to the top element, and adding a new element simply involves placing it on top without the need to move other elements.
Example in Java:
Stack<Integer> stack = new Stack<>();
stack.push(10); // The push operation is performed in O(1)