BudiBadu Logo

First Negative In Every Window

Sliding Window Easy 26 views
Like1

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

Example 1
Input
nums = [12,-1,-7,8,-15,30,16,28], k = 3
Output
[-1,-1,-7,-15,-15,0]
Explanation

Take the first negative in each size-3 window.

Example 2
Input
nums = [1,2,3,4], k = 2
Output
[0,0,0]
Explanation

No window has a negative number.

Example 3
Input
nums = [-5,-2,-3], k = 2
Output
[-5,-2]
Explanation

Each window starts with a negative value.

Algorithm Flow

Recommendation Algorithm Flow for First Negative In Every Window - Budibadu
Recommendation Algorithm Flow for First Negative In Every Window - Budibadu

Best Answers

java
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;
    }
}