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])
- A. [0, 1, 2, 3] 0
- B. [4, 0, 1, 2, 3] 4
- C. [4, 0, 1, 2] 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).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (singly linked list, delete every node whose value equals x) python class N: def init(s, v, n=None): s.v, s.n = v, n h =…
- What is printed? (finding the intersection node of two linked lists by switching heads) python class N: def init(s, v, n=None): s.v, s.n =…
- What is printed? (Java String vs StringBuilder) java String s = "ab"; s.concat("cd"); StringBuilder sb = new StringBuilder("ab")…
- What is printed? (counting sort on small values) python a = [4, 1, 3, 4, 2, 1, 0, 4] cnt = [0] 5 for x in a: cnt[x] += 1 for i in range(1…
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…