BudiBadu Logo

First Negative In Every Window

Sliding Window Easy 3 views
Like0

Given an integer array nums and a window size k, return an array where each element is the first negative number in the corresponding window of length k. If a window contains no negative number, output 0 for that window.

Sliding window is ideal here because windows overlap heavily. A good strategy is to keep a queue (or deque) of indices of negative values that are still inside the current window. For each step, remove expired indices from the front, add the current index if its value is negative, then read the answer from the queue front.

This gives O(n) time because each index enters and leaves the queue at most once.

Example 1:

Input: nums = [12,-1,-7,8,-15,30,16,28], k = 3

Output: [-1,-1,-7,-15,-15,0]

Explanation: For each window of size 3, report the first negative value. The last window has no negative value, so output 0.

Example 2:

Input: nums = [1,2,3,4], k = 2

Output: [0,0,0]

Explanation: None of the windows contain a negative number.

Example 3:

Input: nums = [-5,-2,-3], k = 2

Output: [-5,-2]

Explanation: In each window, the leftmost element is already negative.

Constraints: 1 <= nums.length <= 10^5, 1 <= k <= nums.length

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