This is a very basic problem of implementing a queue operation using two stacks.
Until now there are no issues with the logic but the testing tool report it takes more time than usual.
Test case includes total 100K operations of enqueue, dequeue and show_front. Each item is of 9 digits.
The test tool expects it to be completed by 10 seconds.
I tried with both Python way and traditional algorithmic way but both did not help. I could not find much content with Python list optimization that I can map here.
Listed two of the implementations for reference:
Try 1:
class MyQueue(object):
def __init__(self):
self.stk1 = [] # To store
self.stk2 = [] # To dequeue
def peek(self):
return self.stk1[0]
def pop(self):
for i in range(len(self.stk1)-1):
self.stk2.append(self.stk1.pop())
self.stk1.pop()
for x in range(len(self.stk2)):
self.stk1.append(self.stk2.pop())
def put(self, value):
self.stk1.append(value)
Try 2:
class MyQueue(object):
def __init__(self):
self.stk1 = [] # To store
self.top1 = -1
self.stk2 = [] # To dequeue
self.top2 = -1
def peek(self):
return self.stk1[0]
def pop(self):
if self.top1 == 0:
self.stk1.pop()
self.top1 -= 1
return
while self.top1 > 0:
self.top2 += 1
self.stk2.insert(self.top2,self.stk1.pop(self.top1))
self.top1 -= 1
self.stk1.pop()
self.top1 -= 1
while self.top2 >=0:
self.top1 += 1
self.stk1.insert(self.top1,self.stk2.pop(self.top2))
self.top2 -= 1
def put(self, value):
self.top1 += 1
self.stk1.insert(self.top1,value)
I'm not able to understand if append, insert or pop is taking more time. (Would pre-allocated array of specified size help in Python?)
Note: The testing tool is from a web based platform for developers to practice coding. I am making this question for suggestions about optimization that may help here.
pop
andappend
? \$\endgroup\$pop
orput
, only roll one stack into the other if it's necessary (it would dramatically speed up consecutivepop
s andput
s) \$\endgroup\$