First negative integer in every window of size “k”

Pattern: Sliding window: fixed size

medium

Keep a queue of the indexes of negatives inside the window. New negatives join at the back, indexes that slide out leave from the front, and the front is each window's answer.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers and a window size k. For every block of k neighbouring elements, from left to right, report the first negative number in that block, or 0 if the block has none. Return the n - k + 1 answers. For example, [-8, 2, 3, -6, 10] with k = 2 gives [-8, 0, -6, -6].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name firstNegative is this guide's own. You may assume 1 ≤ k ≤ n.

Think first

  • Rescanning each window costs O(k). Which information carries over from one window to the next?
  • When the window slides, which negatives stop being candidates?
  • Among the negatives inside the window, which one is the answer: the newest or the oldest?

Hints

    Brute force, and why it fails

    For each of the n - k + 1 windows, scan its k elements for the first negative: O(n·k). The queue version is O(n), because each index joins and leaves the queue at most once.

    The key insight

    Negatives leave the window in the same order they entered it. A queue matches that order, so the oldest negative still inside is always at the front.

    Dry run

    120 
    -11 
    -72right
    83 
    -154 
    305 
    166 
    287 
    queue[1, 2]
    out[-1]

    arr = [12, -1, -7, 8, -15, 30, 16, 28] and k = 3. The queue holds indexes of negatives, oldest first. The first window is 12, -1, -7.

    Step 1 of 4

    The plan

    queue = empty, result = empty
    for right from 0 to n - 1:
        if arr[right] < 0: push right to the back of queue
        left = right - k + 1
        if left < 0: continue                      # first window not full yet
        while queue not empty and front of queue < left:
            pop the front                          # slid out of the window
        append (arr[front] if queue not empty else 0) to result
    return result
    

    Complexity

    Time
    O(n)
    Space
    O(k)

    Every index is pushed and popped at most once. The queue only holds indexes inside the window, so at most k of them.

    Edge cases

    • No negatives at all: every answer is 0.
    • k = 1: each answer is the element itself if it is negative, otherwise 0.
    • k = n: one answer, the first negative in the whole array.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] firstNegative(int[] arr, int k) {
            int n = arr.length;
            int[] result = new int[n - k + 1];
            ArrayDeque<Integer> negatives = new ArrayDeque<>();   // indexes of negatives in the window, oldest first
            for (int right = 0; right < n; right++) {
                if (arr[right] < 0) negatives.addLast(right);
                int left = right - k + 1;
                if (left < 0) continue;             // the first window is not full yet
                while (!negatives.isEmpty() && negatives.peekFirst() < left) {
                    negatives.pollFirst();          // this negative has slid out of the window
                }
                result[left] = negatives.isEmpty() ? 0 : arr[negatives.peekFirst()];
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<int> firstNegative(vector<int>& arr, int k) {
            int n = static_cast<int>(arr.size());
            vector<int> result(n - k + 1);
            queue<int> negatives;                   // indexes of negatives in the window, oldest first
            for (int right = 0; right < n; right++) {
                if (arr[right] < 0) negatives.push(right);
                int left = right - k + 1;
                if (left < 0) continue;             // the first window is not full yet
                while (!negatives.empty() && negatives.front() < left) {
                    negatives.pop();                // this negative has slid out of the window
                }
                result[left] = negatives.empty() ? 0 : arr[negatives.front()];
            }
            return result;
        }
    };

    Python

    from collections import deque
    
    
    class Solution:
        def firstNegative(self, arr: list[int], k: int) -> list[int]:
            result = []
            negatives = deque()                     # indexes of negatives in the window, oldest first
            for right, v in enumerate(arr):
                if v < 0:
                    negatives.append(right)
                left = right - k + 1
                if left < 0:
                    continue                        # the first window is not full yet
                while negatives and negatives[0] < left:
                    negatives.popleft()             # this negative has slid out of the window
                result.append(arr[negatives[0]] if negatives else 0)
            return result

    Common mistakes

    • Storing values in the queue instead of indexes, which makes it impossible to tell when a negative has left the window.
    • Removing stale indexes with <= instead of <, which throws away a negative that is still inside.
    • Recording answers before the first window is full.

    Similar problems