Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
O(n) using deque solution in Speedy category for Letter Queue by shuai
from collections import deque
def letter_queue(commands):
"""
Implementation using queue
queue = []
for c in commands:
if c.split()[0] == 'PUSH': queue.append(c.split()[1])
elif c.split()[0] == 'POP' and queue: queue.pop(0)
return ''.join(queue)
"""
d = deque()
for c in commands:
if c.startswith('PUSH'): d.append(c[-1])
elif d: d.popleft()
return ''.join(d)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert letter_queue(["PUSH A", "POP", "POP", "PUSH Z", "PUSH D", "PUSH O", "POP", "PUSH T"]) == "DOT", "dot example"
assert letter_queue(["POP", "POP"]) == "", "Pop, Pop, empty"
assert letter_queue(["PUSH H", "PUSH I"]) == "HI", "Hi!"
assert letter_queue([]) == "", "Nothing"
Oct. 7, 2015