Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (deque operations)

What is printed? (deque operations)
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0); d.append(4)
d.rotate(2)
d.popleft()
print(list(d), d[0])
  1. A. [0, 1, 2, 3] 0
  2. B. [4, 0, 1, 2, 3] 4
  3. C. [4, 0, 1, 2] 4
  4. D. [1, 2, 3, 4] 1

Correct answer: C. [4, 0, 1, 2] 4

After appendleft and append: [0, 1, 2, 3, 4]. rotate(2) moves the last two elements to the front: [3, 4, 0, 1, 2]. popleft removes 3, leaving [4, 0, 1, 2] with 4 at the front. All these deque operations are O(1) (rotate is O(k)), unlike list.insert(0, x).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic