Find the Maximum Element in a Stack in O(1)

Find the maximum element in a stack in O(1) (constant time).

Design a stack to get the maximum element from a stack in constant time.

For example:

To understand this problem, let’s take an example. Suppose, the following elements are pushed in a stack.

push(4)

push(3)

push(9)

push(2)

push(8)

getMax() ( Now, if I call a method to return max element then it should return 9 in O(1)).

pop()

pop()

pop()

getMax() (After three pop operations, If I again call a method to get max element then it should return 4 in O(1)).

Get maximum element from a stack in O(1)

Stack

A stack is a Last In First Out (LIFO) data structure. The element which we pushed at last in a stack is the first element to be popped out from a stack.

So whenever the getMax() method is called how do we return the maximum element from a stack in O(1).

This problem is similar to find the minimum element from a stack in O(1).

Programming video tutorials

Find maximum element in stack in O(1) video tutorial

How to Get Maximum Element form a Stack in O(1)

We can solve this problem by using two stacks. Here are the steps to solve this problem.

i) Declare two stacks. In one stack, we push value as it is. In the second stack, we only push the maximum element present at that time.

ii) Whenever we perform push operation in a stack.

     a) Push the value as it is in a first stack.

   b) For the second stack, push only the maximum value. To get the maximum value, Compare the current value with the value present at the top of the stack.

After this push operation, this is the value present in stack and max stack.

Now you can see, if I call the peek() method on the second stack it can always return the maximum element from a stack in O(1).

Find the Maximum Element in a Stack in O(1) – Java Code

I have already explained its algorithm. Let’s write a java code to implement this algorithm.

Find maximum element in stack in O(1) video tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.