UKD28
UKD28

Reputation: 45

Same logic is working for c++ but not in python for maximum in stack,is there something that i am missing in my code

I have written same logic in python and c++ to return maximum element in a stack in O(1) time using two stacks. but when I submitted it on hackerrank it is showing wrong answer for python but accepting c++. Am I missing something in python.

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n,q,x;
    stack<int>s1,s2;
    cin>>n;
    for(int i = 0;i<n;i++)
    {
        cin>>q;//here q is a type of query
        switch(q)
        {
            //push in stack
            case 1:
                cin>>x;
                if (s1.empty())
                {
                  s2.push(x);
                }
                else 
                {
                  if (x >= s2.top())
                  {
                    s2.push(x);
                  }
                }
                s1.push(x);
                break;
            //pop from stack
            case 2:
                 if(!s1.empty())
                {
                    if(s1.top()==s2.top())
                    {
                        s2.pop();
                    }
                    s1.pop();
                }
                break;
            //getMax from stack
            case 3:
                if(!s2.empty())
                    cout<<s2.top()<<endl;
        }
    }   
    return 0;
}
stack1 = stack2 = []
N = int(input())
for i in range(N):
    a = list(map(int,input().rstrip().split()))
    if a[0]==1:
        if stack1 == []:
            stack2.append(a[1])
        elif a[1]>=stack2[-1]:
            stack2.append(a[1])
        stack1.append(a[1])
    elif a[0]==2:
        if stack1 != []:
            if stack1[-1] == stack2[-1]:
                stack2.pop()
            stack1.pop()
    elif a[0] == 3:
        if stack2 != []:
            print(stack2[-1])

To me it seems same.

I have tried few test cases of my own on other online compiler,they worked same for both. Should I use LIFO from queue module in python , but till now I have not encountered any problem in using lists as a stack before.

They both should work same for all test cases.

Upvotes: 3

Views: 89

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51663

You only have 1 python "stack":

stack1 = stack2 = []     # two names that point to the same list

print(id(stack1))
print(id(stack2))

# vs

stack1 = []              # points to one list
stack2 = []              # points to another list

print(id(stack1))
print(id(stack2))

Output:

139948335562312
139948335562312

# vs

139948335067208
139948335562696

Upvotes: 6

Related Questions