Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices.
Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices.
from collections import deque
def first_neg(a, k):
q, out = deque(), []
for i, x in enumerate(a):
if x < 0: q.append(i)
if q and q[0] <= i - k: q.popleft()
if i >= k - 1: out.append(a[q[0]] if q else 0)
return out
print(first_neg([12, -1, -7, 8, 15, 30, 16, 28], 3))What is printed?- A. [-1, -7, -7, 0, 0, 0]
- B. [-1, -1, -7, -7, 0, 0]
- C. [-1, -1, -7, 0, 0, 0]
- D. [-7, -7, 0, 0, 0, 0]
Correct answer: C. [-1, -1, -7, 0, 0, 0]
Windows: [12, −1, −7] → −1; [−1, −7, 8] → −1; [−7, 8, 15] → −7; [8, 15, 30], [15, 30, 16], [30, 16, 28] → 0. Indices that slide out of the window are dropped from the front of the queue.
More Coding Interview Problems questions
- Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge). python…
- Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values). python class N: def…
- Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent). python class T: def init(s, v): s.v, s.l…
- Problem: List every root-to-leaf path whose values sum to the target. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Count the BST keys within [lo, hi], pruning subtrees that cannot contain answers. python class T: def init(s, v): s.v, s.l, s.r =…
- Problem: Delete a node with two children from a BST by replacing it with its inorder successor; print the preorder afterwards. python…