Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (queue simulation – hot potato with step k)
What is printed? (queue simulation – hot potato with step k)
from collections import deque
q = deque(range(1, 8)); out = []
while len(q) > 1:
q.rotate(-2)
out.append(q.popleft())
print(out, q[0])- A. [3, 6, 2, 7, 5, 1] 3
- B. [2, 4, 6, 1, 5, 3] 7
- C. [3, 6, 1, 5, 2, 7] 4
- D. [3, 6, 2, 7, 5, 1] 4
Correct answer: D. [3, 6, 2, 7, 5, 1] 4
Each round passes the potato twice (rotate left by 2) and eliminates the person now at the front – the Josephus problem with every 3rd person removed. For n = 7, k = 3 the survivor is 4. The deque gives O(k) per elimination.
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? (Josephus recurrence) python def josephus(n, k): r = 0 for m in range(2, n + 1): r = (r + k) % m return r + 1…
- What is printed? (hash set for pairs with a given difference) python def pairsdiff(a, k): s = set(a) return sorted((x, x + k) for x in s…
- What is printed? (Python dict ordering and update) python d = {"b": 1, "a": 2} d["c"] = 3 d["b"] = 4 del d["a"] d["a"] = 5…
- What is printed? (prefix sums for range queries) python a = [3, -2, 5, 1, -4, 6] P = [0] for x in a: P.append(P[-1] + x) q = [(0, 2), (1…
- What is printed? (difference array for range increments) python n = 6 diff = [0] (n + 1) for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5…
- What is printed? (Python sort stability with a key) python recs = [("amit", 82), ("bina", 90), ("chirag", 82), ("dev", 75), ("esha", 90)]…