Skip to content

`deque` queues and double-ended operations [ref]

Problem

  • Remove the leftmost value of deque([1, 2, 3]).
  • Append 4 to the right of deque([1, 2, 3]).
  • Append 0 to the left of deque([1, 2, 3]).
  • Remove the rightmost value of deque([1, 2, 3]).
  • Freeze the length of deque([1, 2]) before appending 3.

Python solution

from collections import deque

q = deque([1, 2, 3])
q.popleft()  # 1
list(q)      # [2, 3]

q = deque([1, 2, 3])
q.append(4)
list(q)  # [1, 2, 3, 4]

q = deque([1, 2, 3])
q.appendleft(0)
list(q)  # [0, 1, 2, 3]

q = deque([1, 2, 3])
q.pop()   # 3
list(q)   # [1, 2]

q = deque([1, 2])
level_size = len(q)
q.append(3)
(level_size, list(q))  # (2, [1, 2, 3])