What is a Stack?

Stack is a basic data structure which could be compared as logical stack in real world scenario. A stack is a limited access data structure - elements can be added and removed from the stack only at the top.

There are mainly 3 functions that are performed on the stack:

push, adds an item to the top of the stack,

pop, removes the item from the top

peek, returns the item from the top without removing it

Stack always perform Last In First Out(LIFO) operation. Consider a stack with elemnts [1, 2, 3, 4, 5]. 5 being at top. Will perform operation on stack

stack = [1,2,3,4,5] operation:popoutput : 5 , stack=[1,2,3,4]

stack = [1,2,3,4] operation:popoutput : 4, stack=[1,2,3]

stack = [1,2,3] operation:push 4output : 4, stack=[1,2,3,4]

stack = [1,2,3,4] operation:peekoutput : 4 , stack=[1,2,3,4]

Anaylsis of Stack Operations

Push an element O(1)

Pop an elementO(1)

Search an element O(n)

Implementation details: One of the basic ways to create a stack is using arrays.