QueueMedium

First Negative Integer Visualizer

What is First Negative Integer

For every window of length k, print the first negative value in that window. If the window has no negative, print 0.

Approach

A fresh scan of each window repeats work. The queue remembers the negatives already seen and drops them when they leave.

Visualization & algorithm

The window and the negatives still inside it
queue holds indexes of negatives
drop the front if it left the window
if a[i] is negative: push i
when the window is full:
answer is a[front], or 0 if the queue is empty
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each index enters and leaves the queue once.
SpaceO(k)At most the negatives inside one window.

Implementation

from collections import deque
def solve(self, nums, k):
    dq, ans = deque(), []
    for i, val in enumerate(nums):
        if dq and dq[0] <= i-k: dq.popleft()
        if val < 0: dq.append(i)
        if i >= k-1:
            ans.append(nums[dq[0]] if dq else 0)
    return ans