Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Sliding Window

First Negative in Every Window

Easy · Sliding Window · Asked at Amazon, Microsoft, TCS, Infosys

For every window of k consecutive elements (from left to right), print the first negative number in that window, or 0 if the window has no negative number.

Input

First line: n k. Second line: n integers.

Output

n − k + 1 numbers separated by spaces.

Constraints

Keep a queue of the indices of negative numbers in the current window. Drop the front when it slides out; the front is the answer.

Example 1

Input

5 2
-8 2 3 -6 10

Output

-8 0 -6 -6

Example 2

Input

8 3
12 -1 -7 8 -15 30 16 28

Output

-1 -1 -7 -15 -15 0

Hints

  1. Scanning each window again is O(n × k).
  2. Only negative numbers matter — remember where they are.
  3. A queue of their indices: the front is the first negative of the window, once the ones that slid out are removed.

Approach

Walk through the array, pushing the index of every negative number onto a queue. When the window [i − k + 1, i] is complete, pop indices from the front while they are ≤ i − k (they have left the window). If the queue is not empty, its front is the answer for this window; otherwise print 0. Every index is pushed and popped at most once.

Complexity: O(n) time · O(k) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (auto &x : a) cin >> x;
    deque<int> q;
    string out;
    for (int i = 0; i < n; i++) {
        if (a[i] < 0) q.push_back(i);
        if (i >= k - 1) {
            while (!q.empty() && q.front() <= i - k) q.pop_front();
            out += to_string(q.empty() ? 0 : a[q.front()]);
            out += (i + 1 < n ? ' ' : '\n');
        }
    }
    cout << out;
    return 0;
}

Python solution

import sys
from collections import deque

data = sys.stdin.buffer.read().split()
n, k = int(data[0]), int(data[1])
a = list(map(int, data[2 : 2 + n]))
q = deque()
out = []
for i in range(n):
    if a[i] < 0:
        q.append(i)
    if i >= k - 1:
        while q and q[0] <= i - k:
            q.popleft()
        out.append(a[q[0]] if q else 0)
print(" ".join(map(str, out)))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int k = (int) in.nval;
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (int) in.nval;
        }
        ArrayDeque<Integer> q = new ArrayDeque<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (a[i] < 0) q.addLast(i);
            if (i >= k - 1) {
                while (!q.isEmpty() && q.peekFirst() <= i - k) q.pollFirst();
                sb.append(q.isEmpty() ? 0 : a[q.peekFirst()]).append(i + 1 < n ? " " : "\n");
            }
        }
        System.out.print(sb);
    }
}

Solve First Negative in Every Window online · All practice problems