What is the best time complexity achievable to find the smallest element stored in a stack?

What is the best time complexity achievable to find the smallest element stored in a stack?

We can, of course, search the entire stack and find the smallest element. However, that approach has a linear time complexity i.e. O(n). But we want to implement this method in O(1) time complexity.

Is a stack O 1?

All the above operations have to be constant time i.e. O(1) operations. We know that stack is a data structure designed to operate in LIFO (Last in First out) context. In stack, a new element is added at one end, and (top) an element is removed from that end only.

How to return the minimum in a stack?

Consider the following Special-Stack 16 –> TOP 15 29 19 18 When getMin () is called it should return 15, which is the minimum element in the current stack. If we do pop two times on stack, the stack becomes 29 –> TOP 19 18 When getMin () is called, it should return 18 which is the minimum in the current stack.

How to support minimum with O ( 1 ) time?

An approach that uses O (1) time and O (n) extra space is discussed here. In this article, a new approach is discussed that supports minimum with O (1) extra space. We define a variable minEle that stores the current minimum element in the stack.

How to pop a stack with getmin ( )?

Pop () : Removes an element from top of stack. Remove element from top. Let the removed element be y. Two cases arise: If y is greater than or equal to minEle, the minimum element in the stack is still minEle. If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle = 2*minEle – y).

How to design a stack to retrieve original elements?

Our task is to design a Data Structure SpecialStack that supports all the stack operations like push (), pop (), isEmpty (), isFull () and an additional operation getMin () which should return minimum element from the SpecialStack. All these operations of SpecialStack must be performed with time complexity O (1).