Count negative elements present in every K-length subarray - GeeksforGeeks

30 Jun, 2021
Given an array arr[] of size N and an integer K, the task is to count the number of negative elements present in all K-length subarrays.
Example:
Input: arr[] = {-1, 2, -2, 3, 5, -7, -5}, K = 3Output: 2 1 1 1 2Explanation: First Subarray: {-1, 2, -2}. Count of negative numbers = 2.Second Subarray: {2, -2, 3}. Count of negative numbers = 1.Third Subarray: {-2, 3, 5}. Count of negative numbers = 1.Fourth Subarray: {3, 5, -7}. Count of negative numbers = 1.Fifth Subarray: {5, -7, -5}. Count of negative numbers = 2.
Input: arr[] = {-1, 2, 4, 4}, K = 2Output: 1 0 0
Naive Approach: The simplest approach is to traverse the given array, considering every window of size K, and find the count of negative numbers in every window. 
Time Complexity: O(N*K)Auxiliary Space: O(1)
Efficient Approach: This problem can be solved using the window sliding technique. Follow the steps below to solve the problem:
Initialize a variable count as 0 to store the count of negative elements in a window of size K.
Initialize two variables i and j as 0 to store the first and last index of the window respectively.
Loop while j<N and perform the following steps:If arr[j] < 0, increment count by 1.If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1.Increment the value of j by 1.
If arr[j] < 0, increment count by 1.
If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1.
Increment the value of j by 1.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to count the number of// negative elements in every window// of size Kvoid countNegative(vector<int> arr, int k){         // Initialize the window pointers    int i = 0;    int j = 0;     // Store the count of negative numbers    int count = 0;    int n = arr.size();     // Traverse the array, arr[]    while (j < n)    {                 // Increase the count        // if element is less then 0        if (arr[j] < 0)        {            count++;        }         // If size of the window equal to k        if (j - i + 1 == k)        {            cout << count << " ";             // If the first element of            // the window is less than 0,            // decrement count by 1            if (arr[i] < 0)            {                count--;            }            i++;        }        j++;    }} // Driver Codeint main(){         // Given Input    vector<int> arr{ -1, 2, -2, 3, 5, -7, -5 };    int k = 3;     // Function Call    countNegative(arr, k);}     // This code is contributed by bgangwar59
// Java program for the above approachimport java.io.*;import java.util.*; class GFG {     // Function to count the number of    // negative elements in every window    // of size K    public static void countNegative(int[] arr, int k)    {        // Initialize the window pointers        int i = 0;        int j = 0;         // Store the count of negative numbers        int count = 0;        int n = arr.length;         // Traverse the array, arr[]        while (j < n) {             // Increase the count            // if element is less then 0            if (arr[j] < 0) {                count++;            }             // If size of the window equal to k            if (j - i + 1 == k) {                System.out.print(count + " ");                 // If the first element of                // the window is less than 0,                // decrement count by 1                if (arr[i] < 0) {                    count--;                }                i++;            }             j++;        }    }     // Driver Code    public static void main(String[] args)    {        // Given Input        int[] arr = { -1, 2, -2, 3, 5, -7, -5 };        int k = 3;         // Function Call        countNegative(arr, k);    }}
# Function to count the number of# negative elements in every window# of size Kdef countNegative(arr,k):         # Initialize the window pointers    i = 0    j = 0         # Store the count of negative numbers    count = 0    n = len(arr)         while(j < n):                 # Increase the count        # if element is less then 0                 if (arr[j] < 0):            count = count + 1                     # If size of the window equal to k          if (j - i + 1 == k):            print(count,end=" ")                         # If the first element of            # the window is less than 0,            # decrement count by 1                         if(arr[i] < 0):                count = count - 1                         i = i+1        j = j+1         # Driver Code # Given Inputarr = [-1, 2, -2, 3, 5, -7, -5]k = 3countNegative(arr, k) # This code is contributed by abhinavjain194.
// C#  program for the above approachusing System; class GFG{ // Function to count the number of// negative elements in every window// of size Kpublic static void countNegative(int[] arr, int k){         // Initialize the window pointers    int i = 0;    int j = 0;     // Store the count of negative numbers    int count = 0;    int n = arr.Length;     // Traverse the array, arr[]    while (j < n)    {                 // Increase the count        // if element is less then 0        if (arr[j] < 0)        {            count++;        }         // If size of the window equal to k        if (j - i + 1 == k)        {            Console.Write(count + " ");             // If the first element of            // the window is less than 0,            // decrement count by 1            if (arr[i] < 0)            {                count--;            }            i++;        }        j++;    }} // Driver Codepublic static void Main(string[] args){         // Given Input    int[] arr = { -1, 2, -2, 3, 5, -7, -5 };    int k = 3;     // Function Call    countNegative(arr, k);}}     // This code is contributed by ukasp
<script>// Javascript program for the above approach // Function to count the number of// negative elements in every window// of size Kfunction countNegative(arr, k){         // Initialize the window pointers    var i = 0;    var j = 0;     // Store the count of negative numbers    var count = 0;    var n = arr.length;     // Traverse the array, arr[]    while (j < n)    {                 // Increase the count        // if element is less then 0        if (arr[j] < 0)        {            count++;        }         // If size of the window equal to k        if (j - i + 1 == k)        {            document.write( count + " ");             // If the first element of            // the window is less than 0,            // decrement count by 1            if (arr[i] < 0)            {                count--;            }            i++;        }        j++;    }} var arr = [ -1, 2, -2, 3, 5, -7, -5 ];var k = 3; // Function CallcountNegative(arr, k); //This code is contributed by SoumikMondal</script>
2 1 1 1 2
 
Time Complexity: O(N)Auxiliary Space: O(1)
 
ukasp
abhinavjain194
bgangwar59
SoumikMondal
sliding-window
subarray
Arrays
Searching
sliding-window
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1