Code Logo

First Negative In Every Window

Published atDate not available
Easy 0 views
Like0

This one is about reading carefully and then following a clear rule. In First Negative In Every Window, you are trying to work toward the right list by following one clear idea.

Return the first negative number for every window of size k (or 0 if none). A good way to think about it is to first understand what goes in, then what rule you must follow, and finally what shape the answer should have.

For example, if the input is nums = [12,-1,-7,8,-15,30,16,28], k = 3, the answer is [-1,-1,-7,-15,-15,0]. Take the first negative in each size-3 window. Another example is nums = [1,2,3,4], k = 2, which gives [0,0,0]. No window has a negative number.

This is a friendly practice problem, but it still rewards careful reading. The key is understanding the rule clearly and then applying it carefully.

One helpful habit is to say the rule out loud in your own words before you start solving. If you can explain what counts, what changes, and what the final answer should look like, you are already much closer to the right solution.

Example Input & Output

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
Recommendation Algorithm Flow for First Negative In Every Window

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