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++
#include <bits/stdc++.h>
using namespace std;
void printFirstNegativeInteger( int arr[], int n, int k)
{
bool flag;
for ( int i = 0; i<(n-k+1); i++)
{
flag = false ;
for ( int j = 0; j<k; j++)
{
if (arr[i+j] < 0)
{
cout << arr[i+j] << " " ;
flag = true ;
break ;
}
}
if (!flag)
cout << "0" << " " ;
}
}
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
import java.util.*;
class solution
{
static void printFirstNegativeInteger( int arr[], int n, int k)
{
boolean flag;
for ( int i = 0 ; i<(n-k+ 1 ); i++)
{
flag = false ;
for ( int j = 0 ; j<k; j++)
{
if (arr[i+j] < 0 )
{
System.out.print((arr[i+j])+ " " );
flag = true ;
break ;
}
}
if (!flag)
System.out.print( "0" + " " );
}
}
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);
}
}
|
Python3
def printFirstNegativeInteger(arr, n, k):
for i in range ( 0 , (n - k + 1 )):
flag = False
for j in range ( 0 , k):
if (arr[i + j] < 0 ):
print (arr[i + j], end = " " )
flag = True
break
if ( not (flag)):
print ( "0" , end = " " )
arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ]
n = len (arr)
k = 3
printFirstNegativeInteger(arr, n, k)
|
C#
using System;
class GFG
{
static void printFirstNegativeInteger( int []arr,
int n, int k)
{
bool flag;
for ( int i = 0; i < (n - k + 1); i++)
{
flag = false ;
for ( int j = 0; j < k; j++)
{
if (arr[i + j] < 0)
{
Console.Write((arr[i + j]) + " " );
flag = true ;
break ;
}
}
if (!flag)
Console.Write( "0" + " " );
}
}
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);
}
}
|
Javascript
<script>
function printFirstNegativeInteger(arr, n, k)
{
let flag;
for (let i = 0; i<(n-k+1); i++)
{
flag = false ;
for (let j = 0; j<k; j++)
{
if (arr[i+j] < 0)
{
document.write((arr[i+j])+ " " );
flag = true ;
break ;
}
}
if (!flag)
document.write( "0" + " " );
}
}
let arr = [12, -1, -7, 8, -15, 30, 16, 28];
let n = arr.length;
let k = 3;
printFirstNegativeInteger(arr, n, k);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
void printFirstNegativeInteger( int arr[], int n, int k)
{
deque< int > Di;
int i;
for (i = 0; i < k; i++)
if (arr[i] < 0)
Di.push_back(i);
for ( ; i < n; i++)
{
if (!Di.empty())
cout << arr[Di.front()] << " " ;
else
cout << "0" << " " ;
while ( (!Di.empty()) && Di.front() < (i - k + 1))
Di.pop_front();
if (arr[i] < 0)
Di.push_back(i);
}
if (!Di.empty())
cout << arr[Di.front()] << " " ;
else
cout << "0" << " " ;
}
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
import java.util.*;
class GFG
{
static void printFirstNegativeInteger( int arr[],
int n, int k)
{
LinkedList<Integer> Di = new LinkedList<>();
int i;
for (i = 0 ; i < k; i++)
if (arr[i] < 0 )
Di.add(i);
for ( ; i < n; i++)
{
if (!Di.isEmpty())
System.out.print(arr[Di.peek()] + " " );
else
System.out.print( "0" + " " );
while ((!Di.isEmpty()) &&
Di.peek() < (i - k + 1 ))
Di.remove();
if (arr[i] < 0 )
Di.add(i);
}
if (!Di.isEmpty())
System.out.print(arr[Di.peek()] + " " );
else
System.out.print( "0" + " " );
}
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);
}
}
|
Python3
from collections import deque
def printFirstNegativeInteger(arr, n, k):
Di = deque()
for i in range (k):
if (arr[i] < 0 ):
Di.append(i);
for i in range (k, n):
if ( not Di):
print ( 0 , end = ' ' )
else :
print (arr[Di[ 0 ]], end = ' ' );
while Di and Di[ 0 ] < = (i - k):
Di.popleft()
if (arr[i] < 0 ):
Di.append(i);
if not Di:
print ( 0 )
else :
print (arr[Di[ 0 ]], end = " " )
if __name__ = = "__main__" :
arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ]
n = len (arr)
k = 3
printFirstNegativeInteger(arr, n, k);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void printFirstNegativeint( int []arr,
int n, int k)
{
List< int > Di = new List< int >();
int i;
for (i = 0; i < k; i++)
if (arr[i] < 0)
Di.Add(i);
for ( ; i < n; i++)
{
if (Di.Count != 0)
Console.Write(arr[Di[0]] + " " );
else
Console.Write( "0" + " " );
while ((Di.Count != 0) &&
Di[0] < (i - k + 1))
Di.RemoveAt(0);
if (arr[i] < 0)
Di.Add(i);
}
if (Di.Count!=0)
Console.Write(arr[Di[0]] + " " );
else
Console.Write( "0" + " " );
}
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);
}
}
|
Javascript
<script>
function printFirstNegativeInteger(arr , n , k)
{
var Di = [];
var i;
for (i = 0; i < k; i++)
if (arr[i] < 0)
Di.push(i);
for (; i < n; i++) {
if (Di.length!==0)
document.write(arr[Di[0]] + " " );
else
document.write( "0" + " " );
while ((Di.length!==0) && Di[0] < (i - k + 1))
Di.shift();
if (arr[i] < 0)
Di.push(i);
}
if (Di.length !== 0)
document.write(arr[Di[0]] + " " );
else
document.write( "0" + " " );
}
var arr = [ 12, -1, -7, 8, -15, 30, 16, 28 ];
var n = arr.length;
var k = 3;
printFirstNegativeInteger(arr, n, k);
</script>
|
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++
#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++) {
while ((firstNegativeIndex < i)
&& (firstNegativeIndex <= i - k
|| arr[firstNegativeIndex] >= 0)) {
firstNegativeIndex++;
}
if (arr[firstNegativeIndex] < 0) {
firstNegativeElement = arr[firstNegativeIndex];
}
else {
firstNegativeElement = 0;
}
cout << firstNegativeElement << " " ;
}
}
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
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++)
{
while ((firstNegativeIndex < i ) &&
(firstNegativeIndex <= i - k ||
arr[firstNegativeIndex] >= 0 ))
{
firstNegativeIndex ++;
}
if (arr[firstNegativeIndex] < 0 )
{
firstNegativeElement = arr[firstNegativeIndex];
}
else
{
firstNegativeElement = 0 ;
}
System.out.print(firstNegativeElement + " " );
}
}
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);
}
}
|
Python3
def printFirstNegativeInteger(arr, k):
firstNegativeIndex = 0
for i in range (k - 1 , len (arr)):
while firstNegativeIndex < i and (firstNegativeIndex < = i - k or arr[firstNegativeIndex] > = 0 ):
firstNegativeIndex + = 1
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)
|
C#
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++)
{
while ((firstNegativeIndex < i ) &&
(firstNegativeIndex <= i - k ||
arr[firstNegativeIndex] >= 0))
{
firstNegativeIndex ++;
}
if (arr[firstNegativeIndex] < 0)
{
firstNegativeElement = arr[firstNegativeIndex];
}
else
{
firstNegativeElement = 0;
}
Console.Write(firstNegativeElement + " " );
}
}
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);
}
}
|
Javascript
<script>
function printFirstNegativeInteger(arr, k, n) {
let firstNegativeIndex = 0;
let firstNegativeElement;
for (let i = k - 1; i < n; i++) {
while ((firstNegativeIndex < i) &&
(firstNegativeIndex <= i - k ||
arr[firstNegativeIndex] >= 0)) {
firstNegativeIndex++;
}
if (arr[firstNegativeIndex] < 0) {
firstNegativeElement = arr[firstNegativeIndex];
}
else {
firstNegativeElement = 0;
}
document.write(firstNegativeElement + " " );
}
}
let arr = [12, -1, -7, 8, -15, 30, 16, 28];
let n = arr.length;
let k = 3;
printFirstNegativeInteger(arr, k, n);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
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++
#include <climits>
#include <cmath> // Need to include <cmath> for the log2() and ceil() functions
#include <iostream>
#include <vector>
using namespace std;
void buildTree(vector< int >& arr, vector< int >& tree,
int start, int end, int index)
{
if (start == end)
tree[index] = arr[start];
else {
int mid = (start + end) / 2;
buildTree(arr, tree, start, mid, 2 * index);
buildTree(arr, tree, mid + 1, end, 2 * index + 1);
tree[index]
= min(tree[2 * index], tree[2 * index + 1]);
}
}
int query(vector< int >& tree, int start, int end, int l,
int r, int index)
{
if (r < start || l > end)
return INT_MAX;
if (l <= start && r >= end)
return tree[index];
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));
}
int main()
{
vector< int > arr = { -8, 2, 3, -6, 10 };
int k = 2;
int n = arr.size();
int treeSize = 2 * (1 << ( int )( ceil (log2(n)))) - 1;
vector< int > tree(treeSize);
buildTree(arr, tree, 0, n - 1, 1);
for ( int i = 0; i <= n - k; i++) {
int minVal = query(tree, 0, n - 1, i, i + k - 1, 1);
if (minVal < 0)
cout << minVal << " " ;
else
cout << "0 " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class SegmentTreeExample {
static void buildTree( int [] arr, int [] tree, int start, int end, int index) {
if (start == end)
tree[index] = arr[start];
else {
int mid = (start + end) / 2 ;
buildTree(arr, tree, start, mid, 2 * index);
buildTree(arr, tree, mid + 1 , end, 2 * index + 1 );
tree[index] = Math.min(tree[ 2 * index], tree[ 2 * index + 1 ]);
}
}
static int query( int [] tree, int start, int end, int l, int r, int index) {
if (r < start || l > end)
return Integer.MAX_VALUE;
if (l <= start && r >= end)
return tree[index];
int mid = (start + end) / 2 ;
return Math.min(query(tree, start, mid, l, r, 2 * index),
query(tree, mid + 1 , end, l, r, 2 * index + 1 ));
}
public static void main(String[] args) {
int [] arr = { - 8 , 2 , 3 , - 6 , 10 };
int k = 2 ;
int n = arr.length;
int treeSize = 2 * ( 1 << ( int ) (Math.ceil(Math.log(n) / Math.log( 2 )))) - 1 ;
int [] tree = new int [treeSize];
buildTree(arr, tree, 0 , n - 1 , 1 );
for ( int i = 0 ; i <= n - k; i++) {
int minVal = query(tree, 0 , n - 1 , i, i + k - 1 , 1 );
if (minVal < 0 )
System.out.print(minVal + " " );
else
System.out.print( "0 " );
}
System.out.println();
}
}
|
Python3
import math
def buildTree(arr, tree, start, end, index):
if start = = end:
tree[index] = arr[start]
else :
mid = (start + end) / / 2
buildTree(arr, tree, start, mid, 2 * index)
buildTree(arr, tree, mid + 1 , end, 2 * index + 1 )
tree[index] = min (tree[ 2 * index], tree[ 2 * index + 1 ])
def query(tree, start, end, l, r, index):
if r < start or l > end:
return math.inf
if l < = start and r > = end:
return tree[index]
mid = (start + end) / / 2
return min (query(tree, start, mid, l, r, 2 * index), query(tree, mid + 1 , end, l, r, 2 * index + 1 ))
if __name__ = = '__main__' :
arr = [ - 8 , 2 , 3 , - 6 , 10 ]
k = 2
n = len (arr)
treeSize = 2 * ( 1 << ( int )(math.ceil(math.log2(n)))) - 1
tree = [ 0 ] * treeSize
buildTree(arr, tree, 0 , n - 1 , 1 )
for i in range (n - k + 1 ):
minVal = query(tree, 0 , n - 1 , i, i + k - 1 , 1 )
if minVal < 0 :
print (minVal, end = " " )
else :
print ( 0 , end = " " )
print ()
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void BuildTree(List< int > arr, List< int > tree,
int start, int end, int index)
{
if (start == end)
tree[index] = arr[start];
else
{
int mid = (start + end) / 2;
BuildTree(arr, tree, start, mid, 2 * index);
BuildTree(arr, tree, mid + 1, end, 2 * index + 1);
tree[index] = Math.Min(tree[2 * index], tree[2 * index + 1]);
}
}
static int Query(List< int > tree, int start, int end, int l, int r, int index)
{
if (r < start || l > end)
return int .MaxValue;
if (l <= start && r >= end)
return tree[index];
int mid = (start + end) / 2;
return Math.Min(Query(tree, start, mid, l, r, 2 * index), Query(tree, mid + 1, end, l, r, 2 * index + 1));
}
static void Main()
{
List< int > arr = new List< int > { -8, 2, 3, -6, 10 };
int k = 2;
int n = arr.Count;
int treeSize = 2 * (1 << ( int )(Math.Log(n) / Math.Log(2)) + 1) - 1;
List< int > tree = new List< int >( new int [treeSize]);
BuildTree(arr, tree, 0, n - 1, 1);
for ( int i = 0; i <= n - k; i++)
{
int minVal = Query(tree, 0, n - 1, i, i + k - 1, 1);
if (minVal < 0)
Console.Write(minVal + " " );
else
Console.Write( "0 " );
}
Console.WriteLine();
}
}
|
Javascript
<script>
function buildTree(arr, tree, start, end, index) {
if (start === end) {
tree[index] = arr[start];
} else {
let mid = Math.floor((start + end) / 2);
buildTree(arr, tree, start, mid, 2 * index);
buildTree(arr, tree, mid + 1, end, 2 * index + 1);
tree[index] = Math.min(tree[2 * index], tree[2 * index + 1]);
}
}
function query(tree, start, end, l, r, index) {
if (r < start || l > end) {
return Infinity;
}
if (l <= start && r >= end) {
return tree[index];
}
let mid = Math.floor((start + end) / 2);
return Math.min(
query(tree, start, mid, l, r, 2 * index),
query(tree, mid + 1, end, l, r, 2 * index + 1)
);
}
let arr = [-8, 2, 3, -6, 10];
let k = 2;
let n = arr.length;
let treeSize = 2 * Math.pow(2, Math.ceil(Math.log2(n))) - 1;
let tree = new Array(treeSize);
buildTree(arr, tree, 0, n - 1, 1);
for (let i = 0; i <= n - k; i++) {
let minVal = query(tree, 0, n - 1, i, i + k - 1, 1);
if (minVal < 0) {
document.write(minVal + " " );
} else {
document.write( "0 " );
}
}
</script>
|
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++
#include <deque>
#include <iostream>
using namespace std;
void printFirstNegative( int arr[], int n, int k)
{
deque< int > negIndices;
for ( int i = 0; i < n; i++) {
if (!negIndices.empty()
&& negIndices.front() == i - k)
negIndices.pop_front();
if (arr[i] < 0)
negIndices.push_back(i);
if (i >= k - 1) {
if (!negIndices.empty())
cout << arr[negIndices.front()] << " " ;
else
cout << "0 " ;
}
}
}
int main()
{
int arr[] = { 12, -1, -7, 8, -15, 30, 16, 28 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
printFirstNegative(arr, n,
k);
return 0;
}
|
Java
import java.util.Deque;
import java.util.LinkedList;
public class Main {
public static void printFirstNegative( int [] arr, int n, int k) {
Deque<Integer> negIndices = new LinkedList<>();
for ( int i = 0 ; i < n; i++) {
if (!negIndices.isEmpty() && negIndices.peekFirst() == i - k) {
negIndices.pollFirst();
}
if (arr[i] < 0 ) {
negIndices.offerLast(i);
}
if (i >= k - 1 ) {
if (!negIndices.isEmpty()) {
System.out.print(arr[negIndices.peekFirst()] + " " );
} else {
System.out.print( "0 " );
}
}
}
}
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);
}
}
|
Python3
from collections import deque
def printFirstNegative(arr, n, k):
negIndices = deque()
for i in range (n):
if negIndices and negIndices[ 0 ] = = i - k:
negIndices.popleft()
if arr[i] < 0 :
negIndices.append(i)
if i > = k - 1 :
if negIndices:
print (arr[negIndices[ 0 ]], end = " " )
else :
print ( "0" , end = " " )
arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ]
n = len (arr)
k = 3
printFirstNegative(arr, n, k)
|
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);
}
static void PrintFirstNegative( int [] arr, int n, int k)
{
Queue< int > negIndices = new Queue< int >();
for ( int i = 0; i < n; i++) {
if (negIndices.Count > 0
&& negIndices.Peek() == i - k) {
negIndices.Dequeue();
}
if (arr[i] < 0) {
negIndices.Enqueue(i);
}
if (i >= k - 1) {
if (negIndices.Count > 0) {
Console.Write(arr[negIndices.Peek()]
+ " " );
}
else {
Console.Write( "0 " );
}
}
}
}
}
|
Javascript
function printFirstNegative(arr, n, k) {
const negIndices = [];
for (let i = 0; i < n; i++) {
if (negIndices.length && negIndices[0] === i - k) {
negIndices.shift();
}
if (arr[i] < 0) {
negIndices.push(i);
}
if (i >= k - 1) {
if (negIndices.length) {
process.stdout.write(arr[negIndices[0]] + ' ' );
}
else {
process.stdout.write( '0 ' );
}
}
}
}
const arr = [12, -1, -7, 8, -15, 30, 16, 28];
const n = arr.length;
const k = 3;
printFirstNegative(arr, n, k);
|
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.
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...