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?
  1. A. [-1, -7, -7, 0, 0, 0]
  2. B. [-1, -1, -7, -7, 0, 0]
  3. C. [-1, -1, -7, 0, 0, 0]
  4. 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

Exams that ask this topic