 GeeksforGeeks App
Open App Browser
Continue

# First negative integer in every window of size k

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 ``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

## 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

## 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

 ``

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 ` `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);``    ``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 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] + ``" "``);``        ` `        ``// 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 < (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] + ``" "``);``    ``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

 ``

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 ``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);``    ``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

 ``

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.

Using Segment Tree:

Basic Idea towards the approach

```The problem requires us to find the first negative integer in each window of size k. To solve this problem efficiently, we can use the segment tree data structure. We can build a segment tree from the input array, where each node in the tree represents a segment of the array. We can store the minimum value of each segment in the node of the segment tree.
To find the first negative integer in each window of size k, we can query the segment tree for the minimum value in each window. If the minimum value in the current window is negative, then it is the first negative integer in that window. Otherwise, we can print 0 for that window.```

Follow the steps below to implement the above idea:

• Define a segment tree data structure that supports range queries for minimum values. The tree should be built from the input array, with each node representing a range of values in the array.
• Traverse the input array, and for each window of size k, query the minimum value from the segment tree. If the minimum value is negative, print it. Otherwise, print 0.
• Implement the segment tree using an array representation, where each node is represented by an index in the array. The root of the tree is at index 0, and for each node at index i, its left child is at index 2i + 1, and its right child is at index 2i + 2.
• To build the segment tree, recursively compute the minimum value for each node in the tree. The minimum value for the root node should be the minimum value of the entire array, and for each non-leaf node, its minimum value should be the minimum of its left and right child nodes.
• To query the minimum value for a given range [l, r], start at the root of the tree and recursively traverse the tree as follows:
• If the current node’s range [i, j] is completely outside the query range [l, r], return a large positive number (such as INT_MAX).
If the current node’s range [i, j] is completely inside the query range [l, r], return the minimum value stored at the node.
Otherwise, recursively query the left and right child nodes, and return the minimum of the two values.
Traverse the input array and for each window of size k, compute the starting and ending indices of the window, and query the minimum value of the range [start_index, end_index] from the segment tree. If the minimum value is negative, print it. Otherwise, print 0.
• Finally, the output will be the list of negative values or 0s for each window of size k in the input array.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the above approach``#include ``#include // Need to include for the log2() and ceil() functions``#include ``#include ` `using` `namespace` `std;` `// Function to build segment tree``void` `buildTree(vector<``int``>& arr, vector<``int``>& tree,``               ``int` `start, ``int` `end, ``int` `index)``{``    ``// If there is only one element in the array, store it``    ``// in the leaf node of the segment tree``    ``if` `(start == end)``        ``tree[index] = arr[start];``    ``else` `{``        ``// Divide the array into two segments and build``        ``// segment tree for each segment recursively``        ``int` `mid = (start + end) / 2;``        ``buildTree(arr, tree, start, mid, 2 * index);``        ``buildTree(arr, tree, mid + 1, end, 2 * index + 1);` `        ``// Store the minimum value of the two segments in``        ``// the current node of the segment tree``        ``tree[index]``            ``= min(tree[2 * index], tree[2 * index + 1]);``    ``}``}` `// Function to query the minimum value in a given range [l,``// r] in the segment tree``int` `query(vector<``int``>& tree, ``int` `start, ``int` `end, ``int` `l,``          ``int` `r, ``int` `index)``{``    ``// If the query range is completely outside the segment``    ``// represented by a node, return infinity``    ``if` `(r < start || l > end)``        ``return` `INT_MAX;` `    ``// If the query range completely overlaps the segment``    ``// represented by a node, return the value of that node``    ``if` `(l <= start && r >= end)``        ``return` `tree[index];` `    ``// Otherwise, divide the segment into two parts and``    ``// recursively find the minimum value of the two parts``    ``int` `mid = (start + end) / 2;``    ``return` `min(``        ``query(tree, start, mid, l, r, 2 * index),``        ``query(tree, mid + 1, end, l, r, 2 * index + 1));``}``// Driver Code``int` `main()``{``    ``// Input array``    ``vector<``int``> arr = { -8, 2, 3, -6, 10 };` `    ``// Window size``    ``int` `k = 2;` `    ``// Calculate the size of the segment tree array``    ``int` `n = arr.size();``    ``int` `treeSize = 2 * (1 << (``int``)(``ceil``(log2(n)))) - 1;` `    ``// Create segment tree``    ``vector<``int``> tree(treeSize);``    ``buildTree(arr, tree, 0, n - 1, 1);` `    ``// Find first negative integer for each window of size k``    ``for` `(``int` `i = 0; i <= n - k; i++) {``        ``// Query the minimum value in the current window``        ``int` `minVal = query(tree, 0, n - 1, i, i + k - 1, 1);` `        ``// If the minimum value is negative, print it,``        ``// otherwise print 0``        ``if` `(minVal < 0)``            ``cout << minVal << ``" "``;``        ``else``            ``cout << ``"0 "``;``    ``}``    ``cout << endl;` `    ``return` `0;``}``// This code is contributed by Veerendra_Singh_Rajpoot`

## Python3

 `# code``import` `math` `# Function to build segment tree``def` `buildTree(arr, tree, start, end, index):``    ``# If there is only one element in the array, store it``    ``# in the leaf node of the segment tree``    ``if` `start ``=``=` `end:``        ``tree[index] ``=` `arr[start]``    ``else``:``        ``# Divide the array into two segments and build``        ``# segment tree for each segment recursively``        ``mid ``=` `(start ``+` `end) ``/``/` `2``        ``buildTree(arr, tree, start, mid, ``2` `*` `index)``        ``buildTree(arr, tree, mid ``+` `1``, end, ``2` `*` `index ``+` `1``)` `        ``# Store the minimum value of the two segments in``        ``# the current node of the segment tree``        ``tree[index] ``=` `min``(tree[``2` `*` `index], tree[``2` `*` `index ``+` `1``])` `# Function to query the minimum value in a given range [l, r] in the segment tree`  `def` `query(tree, start, end, l, r, index):``    ``# If the query range is completely outside the segment``    ``# represented by a node, return infinity``    ``if` `r < start ``or` `l > end:``        ``return` `math.inf` `    ``# If the query range completely overlaps the segment``    ``# represented by a node, return the value of that node``    ``if` `l <``=` `start ``and` `r >``=` `end:``        ``return` `tree[index]` `    ``# Otherwise, divide the segment into two parts and``    ``# recursively find the minimum value of the two parts``    ``mid ``=` `(start ``+` `end) ``/``/` `2``    ``return` `min``(query(tree, start, mid, l, r, ``2` `*` `index), query(tree, mid ``+` `1``, end, l, r, ``2` `*` `index ``+` `1``))`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``# Input array``    ``arr ``=` `[``-``8``, ``2``, ``3``, ``-``6``, ``10``]` `    ``# Window size``    ``k ``=` `2` `    ``# Calculate the size of the segment tree array``    ``n ``=` `len``(arr)``    ``treeSize ``=` `2` `*` `(``1` `<< (``int``)(math.ceil(math.log2(n)))) ``-` `1` `    ``# Create segment tree``    ``tree ``=` `[``0``] ``*` `treeSize``    ``buildTree(arr, tree, ``0``, n ``-` `1``, ``1``)` `    ``# Find first negative integer for each window of size k``    ``for` `i ``in` `range``(n ``-` `k ``+` `1``):``        ``# Query the minimum value in the current window``        ``minVal ``=` `query(tree, ``0``, n ``-` `1``, i, i ``+` `k ``-` `1``, ``1``)` `        ``# If the minimum value is negative, print it,``        ``# otherwise print 0``        ``if` `minVal < ``0``:``            ``print``(minVal, end``=``" "``)``        ``else``:``            ``print``(``0``, end``=``" "``)` `    ``print``()`

Output

`-8 0 -6 -6 `

Time Complexity: O((n + k) log n),

• Building the segment tree takes O(n log n) time, where n is the length of the input array. This is because the tree has at most 4n nodes, and we need to visit each node once to compute its value.
• Querying the minimum value for each window of size k takes O(log n) time, because the height of the tree is log n, and we need to visit at most two nodes at each level of the tree.
• Since we need to do this for each window of size k, the total time complexity of the algorithm is O((n + k) log n).

Space Complexity: O(n),

• Building the segment tree takes O(n) space, because the tree has at most 4n nodes.
• Since we only need to store the segment tree and a few variables to keep track of the indices, the space complexity of the algorithm is O(n).

Using Sliding Window Approach: Follow the steps below to implement the above idea:

• Initialize a deque dq to store the indices of the negative elements, and initialize a variable start to 0.
• Loop through the array from index 0 to n-1, where n is the size of the array.
• If the deque is not empty and the first index in the deque is less than or equal to the current index minus the window size k, remove it from the deque.
• If the current element is negative, add its index to the back of the deque.
• If the current index is greater than or equal to k-1, output the first negative element in the deque. If the deque is empty, output 0.
• Increment the start variable by 1 to move the window to the right.

Below is the implementation for the above approach:

## C++

 `// C++ code to implement the above approach``#include ``#include ``using` `namespace` `std;` `void` `printFirstNegative(``int` `arr[], ``int` `n, ``int` `k)``{``    ``// Create an empty deque to store the indices of``    ``// negative integers``    ``deque<``int``> negIndices;` `    ``// Traverse through the array``    ``for` `(``int` `i = 0; i < n; i++) {``        ``// If the deque is not empty and the leftmost``        ``// element is out of the current window, then remove``        ``// it from the deque``        ``if` `(!negIndices.empty()``            ``&& negIndices.front() == i - k)``            ``negIndices.pop_front();` `        ``// If the current element is negative, add its index``        ``// to the deque``        ``if` `(arr[i] < 0)``            ``negIndices.push_back(i);` `        ``// If the current window is of size k, print the``        ``// first negative integer (if present)``        ``if` `(i >= k - 1) {``            ``// If the deque is not empty, the leftmost``            ``// element is the first negative integer``            ``if` `(!negIndices.empty())``                ``cout << arr[negIndices.front()] << ``" "``;``            ``else``                ``cout << ``"0 "``;``        ``}``    ``}``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 12, -1, -7, 8, -15, 30, 16, 28 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `k = 3;``    ``printFirstNegative(arr, n,``                       ``k); ``// Output: -1 -1 -7 -15 -15 0` `    ``return` `0;``}``// This code is contributed by Veerendra_Singh_Rajpoot`

## Java

 `import` `java.util.Deque;``import` `java.util.LinkedList;` `public` `class` `Main {``    ``public` `static` `void` `printFirstNegative(``int``[] arr, ``int` `n, ``int` `k) {``        ``// Create an empty deque to store the indices of negative integers``        ``Deque negIndices = ``new` `LinkedList<>();` `        ``// Traverse through the array``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``// If the deque is not empty and the leftmost element``            ``// is out of the current window,``           ``// then remove it from the deque``            ``if` `(!negIndices.isEmpty() && negIndices.peekFirst() == i - k) {``                ``negIndices.pollFirst();``            ``}` `            ``// If the current element is negative, add its index to the deque``            ``if` `(arr[i] < ``0``) {``                ``negIndices.offerLast(i);``            ``}` `            ``// If the current window is of size k,``          ``// print the first negative integer (if present)``            ``if` `(i >= k - ``1``) {``                ``// If the deque is not empty,``              ``// the leftmost element is the first negative integer``                ``if` `(!negIndices.isEmpty()) {``                    ``System.out.print(arr[negIndices.peekFirst()] + ``" "``);``                ``} ``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``;``        ``printFirstNegative(arr, n, k); ``// Output: -1 -1 -7 -15 -15 0``    ``}``}`

## Python3

 `from` `collections ``import` `deque`  `def` `printFirstNegative(arr, n, k):` `    ``# Create an empty deque to store the indices of negative integers``    ``negIndices ``=` `deque()` `    ``# Traverse through the array``    ``for` `i ``in` `range``(n):``        ``# If the deque is not empty and``        ``# the leftmost element is out of``        ``# the current window, then remove it from the deque``        ``if` `negIndices ``and` `negIndices[``0``] ``=``=` `i ``-` `k:``            ``negIndices.popleft()` `        ``# If the current element is negative, add its index to the deque``        ``if` `arr[i] < ``0``:``            ``negIndices.append(i)` `        ``# If the current window is of size k,``        ``# print the first negative integer (if present)``        ``if` `i >``=` `k ``-` `1``:``            ``# If the deque is not empty,``            ``# the leftmost element is the first negative integer``            ``if` `negIndices:``                ``print``(arr[negIndices[``0``]], end``=``" "``)``            ``else``:``                ``print``(``"0"``, end``=``" "``)`  `# Driver code``arr ``=` `[``12``, ``-``1``, ``-``7``, ``8``, ``-``15``, ``30``, ``16``, ``28``]``n ``=` `len``(arr)``k ``=` `3``printFirstNegative(arr, n, k)  ``# Output: -1 -1 -7 -15 -15 0`

## C#

 `using` `System;``using` `System.Collections.Generic;` `class` `Program {``  ``static` `void` `Main(``string``[] args)``  ``{``    ``int``[] arr = { 12, -1, -7, 8, -15, 30, 16, 28 };``    ``int` `n = arr.Length;``    ``int` `k = 3;``    ``PrintFirstNegative(arr, n,``                       ``k); ``// Output: -1 -1 -7 -15 -15 0``  ``}` `  ``static` `void` `PrintFirstNegative(``int``[] arr, ``int` `n, ``int` `k)``  ``{``    ``// Create an empty deque to store the indices of``    ``// negative integers``    ``Queue<``int``> negIndices = ``new` `Queue<``int``>();` `    ``// Traverse through the array``    ``for` `(``int` `i = 0; i < n; i++) {``      ``// If the deque is not empty and the leftmost``      ``// element is out of the current window, then``      ``// remove it from the deque``      ``if` `(negIndices.Count > 0``          ``&& negIndices.Peek() == i - k) {``        ``negIndices.Dequeue();``      ``}` `      ``// If the current element is negative, add its``      ``// index to the deque``      ``if` `(arr[i] < 0) {``        ``negIndices.Enqueue(i);``      ``}` `      ``// If the current window is of size k, print the``      ``// first negative integer (if present)``      ``if` `(i >= k - 1) {``        ``// If the deque is not empty, the leftmost``        ``// element is the first negative integer``        ``if` `(negIndices.Count > 0) {``          ``Console.Write(arr[negIndices.Peek()]``                        ``+ ``" "``);``        ``}``        ``else` `{``          ``Console.Write(``"0 "``);``        ``}``      ``}``    ``}``  ``}``}`

## Javascript

 `// JavaScript code to implement the above approach` `function` `printFirstNegative(arr, n, k) {``    ` `    ``// Create an empty deque to store the indices of``    ``// negative integers``    ``const negIndices = [];` `    ``// Traverse through the array``    ``for` `(let i = 0; i < n; i++) {``        ` `        ``// If the deque is not empty and the leftmost``        ``// element is out of the current window,``        ``// then remove it from the deque``        ``if` `(negIndices.length && negIndices === i - k) {``            ``negIndices.shift();``        ``}` `        ``// If the current element is negative, add its index``        ``// to the deque``        ``if` `(arr[i] < 0) {``            ``negIndices.push(i);``        ``}` `        ``// If the current window is of size k, print the``        ``// first negative integer (if present)``        ``if` `(i >= k - 1) {``            ` `            ``// If the deque is not empty, the leftmost``            ``// element is the first negative integer``            ``if` `(negIndices.length) {``                ``process.stdout.write(arr[negIndices] + ``' '``);``            ``}``            ``else` `{``                ``process.stdout.write(``'0 '``);``            ``}``        ``}``    ``}``}` `// Driver code``const arr = [12, -1, -7, 8, -15, 30, 16, 28];``const n = arr.length;``const k = 3;` `printFirstNegative(arr, n, k); ``// Output: -1 -1 -7 -15 -15 0`

Output

`-1 -1 -7 -15 -15 0 `

Time Complexity: O(n), where n is the size of the input array.

Auxiliary Space: O(K) , where K is the Size of the window.

My Personal Notes arrow_drop_up