⬅ Previous Topic
Time Complexity of Stack OperationsNext Topic ⮕
Queues Introduction⬅ Previous Topic
Time Complexity of Stack OperationsNext Topic ⮕
Queues IntroductionSpace complexity refers to the amount of extra memory used by an operation relative to the input size. In the case of stacks, most operations are performed in-place, meaning they work directly within the existing memory block. Below, we explore the space complexity of key stack operations: Push, Pop, Peek, isEmpty, and Traversal.
Operation | Space Complexity | Why? |
---|---|---|
Push | O(1) | Element is added at the top using constant space |
Pop | O(1) | Element is removed from top without new memory |
Peek | O(1) | Accesses the top element directly |
isEmpty | O(1) | Returns true/false using a single flag or count |
Traversal | O(1) to O(N) | O(1) if only reading top; O(N) if visiting all elements |
The push operation inserts an element at the top of the stack. It uses only a fixed amount of memory to store the incoming value.
O(1)
The pop operation removes the top element from the stack.
O(1)
The peek operation reads the top element without removing it.
O(1)
The isEmpty check determines whether the stack is empty.
O(1)
Traversal involves visiting each element in the stack, usually from top to bottom.
O(1)
to O(N)
⬅ Previous Topic
Time Complexity of Stack OperationsNext Topic ⮕
Queues IntroductionYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.