1

The hackerrank problem statement is:

You have an empty sequence, and you will be given queries. Each query is one of these three types:

1 -Push the element x into the stack.

2 -Delete the element present at the top of the stack.

3 -Print the maximum element in the stack.

Input Format

The first line of input contains an integer.

The next lines each contain an above mentioned query. (It is guaranteed that each query is valid.)

Constraints:

Output Format

For each type query, print the maximum element in the stack on a new line.

Sample Input

10 1 97 2 1 20 2 1 26 1 20 2 3 1 91 3

Sample Output

26 91

My code:

n=int(input())
class Stack:
    def __init__(self):
        self.stack1=[]
    def push(self,x):
        return self.stack1.append(x)
    def pop(self):
        self.stack1.pop()
        return
    def maximum(self):
        return max(self.stack1)
stack_object=Stack()
for _ in range(n):
    a=list(map(int,input().split()))
    if a[0]==1:
        stack_object.push(a[1])
    elif a[0]==2:
        stack_object.pop()
    else:
        print(stack_object.maximum()) 

with this algorithm of time complexity O(n^2) I am able to pass 16 out of 27 test cases.

Can someone share a more optimized solution to the problem with time complexity O(n).

Thanks in advance.

mtr_007
  • 59
  • 1
  • 10

2 Answers2

1

There is a simple O(n) algorithms.

Instead of pushing x at the top the stack, simply push max(x, current_top).

Then, the top of the stack will contain the maximum value of all values pushed so far.

Damien
  • 4,809
  • 4
  • 15
  • 20
0

A stack is like a tower of elements. Imagine what each of the actions you listed would look like if it needed to work on tuples rather than numbers, of the form:

(number, h)

where h is the highest element at this level or lower in the tower. For example:

input 1 8 1 6 1 9 1 5 1 10 3 2 3 2 2 3
query  out  stack
1 8         [(8, 8)]
1 6         [(8, 8), (6, 8)]
1 9         [(8, 8), (6, 8), (9, 9)]
1 5         [(8, 8), (6, 8), (9, 9), (5, 9)]
1 10        [(8, 8), (6, 8), (9, 9), (5, 9), (10, 10)]
3      10
2           [(8, 8), (6, 8), (9, 9), (5, 9)]
3      9
2           [(8, 8), (6, 8), (9, 9)]
2           [(8, 8), (6, 8)]
3      8

Working code:

n=int(input())
class Stack:
    def __init__(self):
        self.stack1=[(None, -float('inf'))]
    def push(self,x):
        return self.stack1.append((x, max(self.maximum(), x)))
    def pop(self):
        self.stack1.pop()
        return
    def maximum(self):
        return self.stack1[-1][1]
stack_object=Stack()
for _ in range(n):
    a=list(map(int,input().split()))
    if a[0]==1:
        stack_object.push(a[1])
    elif a[0]==2:
        stack_object.pop()
    else:
        print(stack_object.maximum()) 
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61
  • But as tuples are immutable I am not sure if push or append operation would workout on using tuples instead of numbers.Furthur I am not sure if this idea would not solve the problem under time constraints. – mtr_007 May 08 '20 at 12:55
  • @mtr_007 can you please share a link to the online judge? – גלעד ברקן May 08 '20 at 13:06
  • @mtr_007 didn't the solution by Damien work for you? – גלעד ברקן May 08 '20 at 13:07
  • the link to the problem is-https://www.hackerrank.com/challenges/maximum-element/problem – mtr_007 May 09 '20 at 14:10
  • @mtr_007 added passing code to demonstrate. This is the same idea as Damien's, just more general in that we can still get the actual stack elements, which as they pointed out, is not needed for this task. – גלעד ברקן May 09 '20 at 17:35
  • self.stack1=[(None, -float('inf'))] Please explain this stack initialization. You have defined stack using list with data type float but what is float('inf') ? I am not getting this. – mtr_007 May 10 '20 at 05:08
  • @mtr_007 `-float('inf')` is an [unbounded low value](https://stackoverflow.com/questions/34264710/what-is-the-point-of-floatinf-in-python) so as to always make the first element added the first maximum. – גלעד ברקן May 10 '20 at 10:32
  • Thanks for the help.This is insightful. – mtr_007 May 10 '20 at 16:31