First Negative In Every Window
First Negative In Every Window asks you to slide a fixed window of size k across an integer array and report the first negative value inside each window. If a window has no negative values, output 0 for that position. The result is an array aligned with each valid window in left-to-right order.
The efficient pattern is a queue/deque of indices for negative elements currently inside the window. As you move the window, drop indices that fall out on the left, push the current index if its value is negative, then read the front as the first negative for that window. If the queue is empty, append 0.
The judge includes windows with all positives, all negatives, mixed signs, and edge cases where k may exceed array length. Your function should return a clean integer array and maintain strict order. Each index should enter and leave the deque at most once, giving linear-time behavior and reliable performance for larger inputs.
Examples
Take the first negative in each size-3 window.
No window has a negative number.
Each window starts with a negative value.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int[] first_negative_in_every_window(int[] nums, int k) {
int n = nums.length;
if (k <= 0 || k > n) return new int[0];
Deque<Integer> q = new ArrayDeque<>();
int[] ans = new int[n - k + 1];
int t = 0;
for (int i = 0; i < n; i++) {
if (nums[i] < 0) q.offerLast(i);
while (!q.isEmpty() && q.peekFirst() <= i - k) q.pollFirst();
if (i >= k - 1) ans[t++] = q.isEmpty() ? 0 : nums[q.peekFirst()];
}
return ans;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
