Skip to content
Related Articles
Open in App
Not now

Related Articles

First negative integer in every window of size k

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 12 Sep, 2022
Improve Article
Save Article

Given an array and a positive integer k, find the first negative integer for each window(contiguous subarray) of size k. If a window does not contain a negative integer, then print 0 for that window.

Examples:  

Input : arr[] = {-8, 2, 3, -6, 10}, k = 2
Output : -8 0 -6 -6

First negative integer for each window of size k
{-8, 2} = -8
{2, 3} = 0 (does not contain a negative integer)
{3, -6} = -6
{-6, 10} = -6

Input : arr[] = {12, -1, -7, 8, -15, 30, 16, 28} , k = 3
Output : -1 -1 -7 -15 -15 0

Run two loops. In the outer loop, take all subarrays(windows) of size k. In the inner loop, get the first negative integer of the current subarray(window).

C++




// C++ implementation to find the first negative
// integer in every window of size k
#include <bits/stdc++.h>
using namespace std;
  
// function to find the first negative
// integer in every window of size k
void printFirstNegativeInteger(int arr[], int n, int k)
{
    // flag to check whether window contains
    // a negative integer or not
    bool flag;
     
    // Loop for each subarray(window) of size k
    for (int i = 0; i<(n-k+1); i++)          
    {
        flag = false;
 
        // traverse through the current window
        for (int j = 0; j<k; j++)
        {
            // if a negative integer is found, then
            // it is the first negative integer for
            // current window. Print it, set the flag
            // and break
            if (arr[i+j] < 0)
            {
                cout << arr[i+j] << " ";
                flag = true;
                break;
            }
        }
         
        // if the current window does not
        // contain a negative integer
        if (!flag)
            cout << "0" << " ";
    }   
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
    printFirstNegativeInteger(arr, n, k);
    return 0;
}

Java




// Java implementation to find the first negative
// integer in every window of size k
import java.util.*;
 
class solution
{
 
// function to find the first negative
// integer in every window of size k
static void printFirstNegativeInteger(int arr[], int n, int k)
{
    // flag to check whether window contains
    // a negative integer or not
    boolean flag;
     
    // Loop for each subarray(window) of size k
    for (int i = 0; i<(n-k+1); i++)        
    {
        flag = false;
 
        // traverse through the current window
        for (int j = 0; j<k; j++)
        {
            // if a negative integer is found, then
            // it is the first negative integer for
            // current window. Print it, set the flag
            // and break
            if (arr[i+j] < 0)
            {
                System.out.print((arr[i+j])+" ");
                flag = true;
                break;
            }
        }
         
        // if the current window does not
        // contain a negative integer
        if (!flag)
            System.out.print("0"+" ");
    }
}
 
// Driver program to test above functions
public static void main(String args[])
{
    int arr[] = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = arr.length;
    int k = 3;
    printFirstNegativeInteger(arr, n, k);
     
}
}
// This code is contributed by
// Shashank_Sharma

Python3




# Python3 implementation to find the first negative
# integer in every window of size k
 
# Function to find the first negative
# integer in every window of size k
def printFirstNegativeInteger(arr, n, k):
     
    # Loop for each subarray(window) of size k
    for i in range(0, (n - k + 1)):
        flag = False
 
        # Traverse through the current window
        for j in range(0, k):
         
            # If a negative integer is found, then
            # it is the first negative integer for
            # current window. Print it, set the flag
            # and break
            if (arr[i + j] < 0):
         
                print(arr[i + j], end = " ")
                flag = True
                break
         
        # If the current window does not
        # contain a negative integer
        if (not(flag)):
            print("0", end = " ")
     
# Driver Code
arr = [12, -1, -7, 8, -15, 30, 16, 28]
n = len(arr)
k = 3
printFirstNegativeInteger(arr, n, k)
 
# This code is contributed by 'Smitha dinesh semwal'

C#




// C# implementation to find
// the first negative integer
// in every window of size k
using System;
 
class GFG
{
 
// function to find the first negative
// integer in every window of size k
static void printFirstNegativeInteger(int []arr,
                                    int n, int k)
{
    // flag to check whether window contains
    // a negative integer or not
    bool flag;
     
    // Loop for each subarray(window) of size k
    for (int i = 0; i < (n - k + 1); i++)
    {
        flag = false;
 
        // traverse through the current window
        for (int j = 0; j < k; j++)
        {
            // if a negative integer is found, then
            // it is the first negative integer for
            // current window. Print it, set the flag
            // and break
            if (arr[i + j] < 0)
            {
                Console.Write((arr[i + j]) + " ");
                flag = true;
                break;
            }
        }
         
        // if the current window does not
        // contain a negative integer
        if (!flag)
            Console.Write("0" + " ");
    }
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = arr.Length;
    int k = 3;
    printFirstNegativeInteger(arr, n, k);
}
}
 
// This code has been contributed
// by 29AjayKumar

Javascript




<script>
 
// JavaScript implementation to find
// the first negative integer
// in every window of size k
function printFirstNegativeInteger(arr, n, k)
{
    // flag to check whether window contains
    // a negative integer or not
    let flag;
     
    // Loop for each subarray(window) of size k
    for (let i = 0; i<(n-k+1); i++)        
    {
        flag = false;
 
        // traverse through the current window
        for (let j = 0; j<k; j++)
        {
            // if a negative integer is found, then
            // it is the first negative integer for
            // current window. Print it, set the flag
            // and break
            if (arr[i+j] < 0)
            {
                document.write((arr[i+j])+" ");
                flag = true;
                break;
            }
        }
         
        // if the current window does not
        // contain a negative integer
        if (!flag)
            document.write("0"+" ");
    }
}
 
    // Driver Code
     
    let arr = [12, -1, -7, 8, -15, 30, 16, 28];
    let n = arr.length;
    let k = 3;
    printFirstNegativeInteger(arr, n, k);
 
// This code is contributed by avijitmondal1998.
</script>

Output

-1 -1 -7 -15 -15 0 

Time Complexity : The outer loop runs n-k+1 times and the inner loop runs k times for every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written as O(nk) when k is comparatively much smaller than n, otherwise when k tends to reach n, complexity becomes O(k). 

Auxiliary Space: O(1) as it is using constant space for variables

Approach 2: Efficient Approach

We create a Dequeue, Di of capacity k, that stores only useful elements of the current window of k elements. An element is useful if it is in the current window and it is a negative integer. We process all array elements one by one and maintain Di to contain useful elements of current window and these useful elements are all negative integers. For a particular window, if Di is not empty then the element at front of the Di is the first negative integer for that window, else that window does not contain a negative integer.

It is a variation of the problem of Sliding Window Maximum

Implementation:

C++




// C++ implementation to find the first negative
// integer in every window of size k
#include <bits/stdc++.h>
 
using namespace std;
  
// function to find the first negative
// integer in every window of size k
void printFirstNegativeInteger(int arr[], int n, int k)
{
    // A Double Ended Queue, Di that will store indexes of
    // useful array elements for the current window of size k.
    // The useful elements are all negative integers.
    deque<int>  Di;
  
    /* Process first k (or first window) elements of array */
    int i;
    for (i = 0; i < k; i++)
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.push_back(i);
     
    // Process rest of the elements, i.e., from arr[k] to arr[n-1]
    for ( ; i < n; i++)
    {
        // if Di is not empty then the element at the
        // front of the queue is the first negative integer
        // of the previous window
        if (!Di.empty())
            cout << arr[Di.front()] << " ";
         
        // else the window does not have a
        // negative integer
        else
            cout << "0" << " ";
  
        // Remove the elements which are out of this window
        while ( (!Di.empty()) && Di.front() < (i - k + 1))
            Di.pop_front();  // Remove from front of queue
  
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.push_back(i);
    }
  
    // Print the first negative
    // integer of last window
    if (!Di.empty())
           cout << arr[Di.front()] << " ";
    else
        cout << "0" << " ";      
     
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
    printFirstNegativeInteger(arr, n, k);
    return 0;
}

Java




// Java implementation to find the
// first negative integer in
// every window of size k
import java.util.*;
class GFG
{
 
// function to find the first negative
// integer in every window of size k
static void printFirstNegativeInteger(int arr[],
                                      int n, int k)
{
    // A Double Ended Queue, Di that will
    // store indexes of useful array elements
    // for the current window of size k.
    // The useful elements are all negative integers.
    LinkedList<Integer> Di = new LinkedList<>();
 
    // Process first k (or first window)
    // elements of array
    int i;
    for (i = 0; i < k; i++)
     
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.add(i);
     
    // Process rest of the elements,
    // i.e., from arr[k] to arr[n-1]
    for ( ; i < n; i++)
    {
        // if Di is not empty then the element
        // at the front of the queue is the first
        // negative integer of the previous window
        if (!Di.isEmpty())
            System.out.print(arr[Di.peek()] + " ");
         
        // else the window does not have a
        // negative integer
        else
            System.out.print("0" + " ");
 
        // Remove the elements which are
        // out of this window
        while ((!Di.isEmpty()) &&
                 Di.peek() < (i - k + 1))
            Di.remove(); // Remove from front of queue
 
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.add(i);
    }
 
    // Print the first negative
    // integer of last window
    if (!Di.isEmpty())
        System.out.print(arr[Di.peek()] + " ");
    else
        System.out.print("0" + " ");    
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = arr.length;
    int k = 3;
    printFirstNegativeInteger(arr, n, k);
}
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python3 implementation to find the
# first negative integer in every window
# of size k import deque() from collections
from collections import deque
 
# function to find the first negative
# integer in every window of size k
def printFirstNegativeInteger(arr, n, k):
     
    # A Double Ended Queue, Di that will store
    # indexes of useful array elements for the
    # current window of size k. The useful
    # elements are all negative integers.
    Di = deque()
 
    # Process first k (or first window)
    # elements of array
    for i in range(k):
         
        # Add current element at the rear of Di
        # if it is a negative integer
        if (arr[i] < 0):
            Di.append(i);
     
    # Process rest of the elements, i.e.,
    # from arr[k] to arr[n-1]
    for i in range(k, n):
         
        # if the window does not have
        # a negative integer
        if (not Di):
            print(0, end = ' ')
         
        # if Di is not empty then the element
        # at the front of the queue is the first
        # negative integer of the previous window
        else:
            print(arr[Di[0]], end = ' ');
 
        # Remove the elements which are
        # out of this window
        while Di and Di[0] <= (i - k):
            Di.popleft() # Remove from front of queue
 
        # Add current element at the rear of Di
        # if it is a negative integer
        if (arr[i] < 0):
            Di.append(i);
 
    # Print the first negative
    # integer of last window
    if not Di:
        print(0)
    else:
        print(arr[Di[0]], end = " ")
     
# Driver Code
if __name__ =="__main__":
    arr = [12, -1, -7, 8, -15, 30, 16, 28]
    n = len(arr)
    k = 3
    printFirstNegativeInteger(arr, n, k);
 
# This code is contributed by
# chaudhary_19 (Mayank Chaudhary)

C#




// C# implementation to find the
// first negative integer in
// every window of size k
using System;
using System.Collections.Generic;
 
class GFG
{
 
// function to find the first negative
// integer in every window of size k
static void printFirstNegativeint(int []arr,
                                  int n, int k)
{
    // A Double Ended Queue, Di that will
    // store indexes of useful array elements
    // for the current window of size k.
    // The useful elements are all
    // negative integers.
    List<int> Di = new List<int>();
 
    // Process first k (or first window)
    // elements of array
    int i;
    for (i = 0; i < k; i++)
     
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.Add(i);
     
    // Process rest of the elements,
    // i.e., from arr[k] to arr[n-1]
    for ( ; i < n; i++)
    {
        // if Di is not empty then the element
        // at the front of the queue is the first
        // negative integer of the previous window
        if (Di.Count != 0)
            Console.Write(arr[Di[0]] + " ");
         
        // else the window does not have a
        // negative integer
        else
            Console.Write("0" + " ");
 
        // Remove the elements which are
        // out of this window
        while ((Di.Count != 0) &&
                Di[0] < (i - k + 1))
                 
            // Remove from front of queue
            Di.RemoveAt(0);
 
        // Add current element at the rear of Di
        // if it is a negative integer
        if (arr[i] < 0)
            Di.Add(i);
    }
 
    // Print the first negative
    // integer of last window
    if (Di.Count!=0)
        Console.Write(arr[Di[0]] + " ");
    else
        Console.Write("0" + " ");    
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = {12, -1, -7, 8, -15, 30, 16, 28};
    int n = arr.Length;
    int k = 3;
    printFirstNegativeint(arr, n, k);
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// javascript implementation to find the
// first negative integer in
// every window of size k
 
    // function to find the first negative
    // integer in every window of size k
    function printFirstNegativeInteger(arr , n , k)
    {
     
        // A Double Ended Queue, Di that will
        // store indexes of useful array elements
        // for the current window of size k.
        // The useful elements are all negative integers.
        var Di = [];
 
        // Process first k (or first window)
        // elements of array
        var i;
        for (i = 0; i < k; i++)
 
            // Add current element at the rear of Di
            // if it is a negative integer
            if (arr[i] < 0)
                Di.push(i);
 
        // Process rest of the elements,
        // i.e., from arr[k] to arr[n-1]
        for (; i < n; i++) {
            // if Di is not empty then the element
            // at the front of the queue is the first
            // negative integer of the previous window
            if (Di.length!==0)
                document.write(arr[Di[0]] + " ");
 
            // else the window does not have a
            // negative integer
            else
                document.write("0" + " ");
 
            // Remove the elements which are
            // out of this window
            while ((Di.length!==0) && Di[0] < (i - k + 1))
                Di.shift(); // Remove from front of queue
 
            // Add current element at the rear of Di
            // if it is a negative integer
            if (arr[i] < 0)
                Di.push(i);
        }
 
        // Print the first negative
        // integer of last window
        if (Di.length !== 0)
            document.write(arr[Di[0]] + " ");
        else
            document.write("0" + " ");
    }
 
    // Driver Code
     
        var arr = [ 12, -1, -7, 8, -15, 30, 16, 28 ];
        var n = arr.length;
        var k = 3;
        printFirstNegativeInteger(arr, n, k);
 
// This code is contributed by Rajput-Ji
</script>

Output

-1 -1 -7 -15 -15 0 

Time Complexity: O(n) 

Auxiliary Space: O(k)

Optimized Approach:: It is also possible to accomplish this with constant space. The idea is to have a variable firstNegativeIndex to keep track of the first negative element in the k sized window. At every iteration, we skip the elements which no longer fall under the current k size window (firstNegativeIndex <= i – k) as well as the non-negative elements(zero or positive). 

Below is the solution based on this approach.

C++




// C++ code for First negative integer
// in every window of size k
#include <iostream>
using namespace std;
 
void printFirstNegativeInteger(int arr[], int k, int n)
{
    int firstNegativeIndex = 0;
    int firstNegativeElement;
 
    for (int i = k - 1; i < n; i++) {
 
        // skip out of window and positive elements
        while ((firstNegativeIndex < i)
               && (firstNegativeIndex <= i - k
                   || arr[firstNegativeIndex] >= 0)) {
            firstNegativeIndex++;
        }
 
        // check if a negative element is found, otherwise
        // use 0
        if (arr[firstNegativeIndex] < 0) {
            firstNegativeElement = arr[firstNegativeIndex];
        }
        else {
            firstNegativeElement = 0;
        }
        cout << firstNegativeElement << " ";
    }
}
 
// Driver code
int main()
{
    int arr[] = { 12, -1, -7, 8, -15, 30, 16, 28 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    printFirstNegativeInteger(arr, k, n);
}

Java




// Java code for First negative integer
// in every window of size k
import java.util.*;
 
class GFG{
     
static void printFirstNegativeInteger(int arr[],
                                      int k, int n)
{
    int firstNegativeIndex = 0;
    int firstNegativeElement;
     
    for(int i = k - 1; i < n; i++)
    {
         
        // Skip out of window and positive elements
        while ((firstNegativeIndex < i ) &&
               (firstNegativeIndex <= i - k ||
            arr[firstNegativeIndex] >= 0))
        {
            firstNegativeIndex ++;
        }
         
        // Check if a negative element is
        // found, otherwise use 0
        if (arr[firstNegativeIndex] < 0)
        {
            firstNegativeElement = arr[firstNegativeIndex];
        }
        else
        {
            firstNegativeElement = 0;
        }
        System.out.print(firstNegativeElement + " ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 12, -1, -7, 8, -15, 30, 16, 28 };
    int n = arr.length;
    int k = 3;
     
    printFirstNegativeInteger(arr, k, n);   
}
}
 
// This code is contributed by amreshkumar3

Python3




# Python3 code for First negative integer
# in every window of size k
def printFirstNegativeInteger(arr, k):
    firstNegativeIndex = 0
 
    for i in range(k - 1, len(arr)):
 
        # skip out of window and positive elements
        while firstNegativeIndex < i and (firstNegativeIndex <= i - k or arr[firstNegativeIndex] >= 0):
            firstNegativeIndex += 1
 
        # check if a negative element is found, otherwise use 0
        firstNegativeElement = arr[firstNegativeIndex] if arr[firstNegativeIndex] < 0 else 0
        print(firstNegativeElement, end=' ')
 
 
if __name__ == "__main__":
    arr = [12, -1, -7, 8, -15, 30, 16, 28]
    k = 3
    printFirstNegativeInteger(arr, k)
 
# contributed by Arjun Lather

C#




// C# code for First negative integer
// in every window of size k
using System;
 
class GFG{
 
static void printFirstNegativeInteger(int[] arr,
                                      int k, int n)
{
    int firstNegativeIndex = 0;
    int firstNegativeElement;
     
    for(int i = k - 1; i < n; i++)
    {
         
        // Skip out of window and positive elements
        while ((firstNegativeIndex < i ) &&
               (firstNegativeIndex <= i - k ||
            arr[firstNegativeIndex] >= 0))
        {
            firstNegativeIndex ++;
        }
         
        // Check if a negative element is
        // found, otherwise use 0
        if (arr[firstNegativeIndex] < 0)
        {
            firstNegativeElement = arr[firstNegativeIndex];
        }
        else
        {
            firstNegativeElement = 0;
        }
        Console.Write(firstNegativeElement + " ");
    }   
}
 
// Driver code
static public void Main()
{
    int[] arr = { 12, -1, -7, 8, -15, 30, 16, 28 };
    int n = arr.Length;
    int k = 3;
     
    printFirstNegativeInteger(arr, k, n);
}
}
 
// This code is contributed by rag2127

Javascript




<script>
        // JavaScript Program for the above approach
 
 
 
        function printFirstNegativeInteger(arr, k, n) {
            let firstNegativeIndex = 0;
            let firstNegativeElement;
 
 
            for (let i = k - 1; i < n; i++) {
 
                // skip out of window and positive elements
                while ((firstNegativeIndex < i) &&
                    (firstNegativeIndex <= i - k ||
                        arr[firstNegativeIndex] >= 0)) {
                    firstNegativeIndex++;
                }
 
                // check if a negative element is found, otherwise use 0
                if (arr[firstNegativeIndex] < 0) {
                    firstNegativeElement = arr[firstNegativeIndex];
                }
                else {
                    firstNegativeElement = 0;
                }
                document.write(firstNegativeElement + " ");
            }
 
        }
 
        // Driver code
 
        let arr = [12, -1, -7, 8, -15, 30, 16, 28];
        let n = arr.length;
        let k = 3;
        printFirstNegativeInteger(arr, k, n);
 
    // This code is contributed by Potta Lokesh
    </script>

Output

-1 -1 -7 -15 -15 0 

Time Complexity: O(n) 

Auxiliary Space: O(1)

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on GeeksforGeek’s main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!