Implement a queue using two stacks
The space cost is O(n). The runtime cost of enqueue is O(1); the runtime cost of dequeue is O(n). Using the "accounting method", the cost of an item in the system is O(1). Here's why: +------------+----------------------------+------+ | enqueue | push onto lhs | O(1) | +------------+----------------------------+------+ | lhs -> rhs | pop off lhs; push onto rhs | O(1) | +------------+----------------------------+------+ | dequeue | pop off rhs | O(1) | +------------+----------------------------+------+
This commit is contained in:
parent
417d3b5fff
commit
60d7ea5b91
1 changed files with 17 additions and 0 deletions
17
scratch/facebook/interview-cake/queue-two-stacks.py
Normal file
17
scratch/facebook/interview-cake/queue-two-stacks.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
class Queue(object):
|
||||
def __init__(self):
|
||||
self.lhs = []
|
||||
self.rhs = []
|
||||
|
||||
def enqueue(self, x):
|
||||
self.lhs.append(x)
|
||||
|
||||
def dequeue(self):
|
||||
if self.rhs:
|
||||
return self.rhs.pop()
|
||||
while self.lhs:
|
||||
self.rhs.append(self.lhs.pop())
|
||||
if self.rhs:
|
||||
return self.rhs.pop()
|
||||
else:
|
||||
raise Exception("Attempting to remove an item from an empty queue")
|
Loading…
Reference in a new issue