First negative integer in every window of size k
Last Updated :
14 May, 2025
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, 1] , k = 2
Output: [-8, 0, -6, -6]
Explanation: First negative integer for each window of size 2
[-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]
Explanation: First negative integer for each window of size 3
[ 12, -1, -7] = -1
[-1,-7, 8] = -1
[-7, 8, -15] = -7
[8, -15, 30] = -15
[-15, 30, 16] = -15
[30, 16, 28] = 0
[Naive Approach] Nested Loops - O(n*k) time and O(1) space
The idea is to loop through the array, and for each window of size k, check each element to find the first negative number. If a negative number is found, it is printed immediately, and the inner loop breaks. If no negative number is found in the window, it prints 0
. This ensures that each window is processed individually, and the result is output for all windows in sequence.
C++
#include <bits/stdc++.h>
using namespace std;
// function to find the first negative integer
// in every window of size k
vector<int> firstNegInt(vector<int>& arr, int k) {
vector<int> res;
int n = arr.size();
// Loop for each subarray(window) of size k
for (int i = 0; i <= (n - k); i++) {
bool found = 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
// the current window. Set the flag and break
if (arr[i + j] < 0) {
res.push_back(arr[i + j]);
found = true;
break;
}
}
// if the current window does not contain
// a negative integer
if (!found) {
res.push_back(0);
}
}
return res;
}
int main() {
vector<int> arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
vector<int> res = firstNegInt(arr, k);
cout << "[";
for (int i = 0; i < res.size(); i++) {
cout << res[i];
if (i < res.size() - 1) {
cout << ", ";
}
}
cout << "]";
return 0;
}
Java
import java.util.*;
// function to find the first negative integer
// in every window of size k
public class GfG {
public static int[] firstNegInt(int[] arr, int k) {
List<Integer> res = new ArrayList<>();
int n = arr.length;
// Loop for each subarray(window) of size k
for (int i = 0; i <= (n - k); i++) {
boolean found = 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
// the current window. Set the flag and break
if (arr[i + j] < 0) {
res.add(arr[i + j]);
found = true;
break;
}
}
// if the current window does not contain
// a negative integer
if (!found) {
res.add(0);
}
}
// Convert List to int[]
return res.stream().mapToInt(i -> i).toArray();
}
public static void main(String[] args) {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
int[] res = firstNegInt(arr, k);
System.out.print(Arrays.toString(res));
}
}
Python
# function to find the first negative integer
# in every window of size k
def firstNegInt(arr, k):
res = []
n = len(arr)
# Loop for each subarray(window) of size k
for i in range(n - k + 1):
found = False
# traverse through the current window
for j in range(k):
# if a negative integer is found, then
# it is the first negative integer for
# the current window. Set the flag and break
if arr[i + j] < 0:
res.append(arr[i + j])
found = True
break
# if the current window does not contain
# a negative integer
if not found:
res.append(0)
return res
arr = [12, -1, -7, 8, -15, 30, 16, 28]
k = 3
res = firstNegInt(arr, k)
print(res)
C#
using System;
using System.Collections.Generic;
class GfG {
// function to find the first negative integer
// in every window of size k
public static List<int> FirstNegInt(int[] arr, int k) {
List<int> res = new List<int>();
int n = arr.Length;
// Loop for each subarray(window) of size k
for (int i = 0; i <= (n - k); i++) {
bool found = 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
// the current window. Set the flag and break
if (arr[i + j] < 0) {
res.Add(arr[i + j]);
found = true;
break;
}
}
// if the current window does not contain
// a negative integer
if (!found) {
res.Add(0);
}
}
return res;
}
static void Main() {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
List<int> res = FirstNegInt(arr, k);
Console.WriteLine("[" + string.Join(", ", res) + "]");
}
}
JavaScript
// function to find the first negative integer
// in every window of size k
function firstNegInt(arr, k) {
let res = [];
let n = arr.length;
// Loop for each subarray(window) of size k
for (let i = 0; i <= (n - k); i++) {
let found = 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
// the current window. Set the flag and break
if (arr[i + j] < 0) {
res.push(arr[i + j]);
found = true;
break;
}
}
// if the current window does not contain
// a negative integer
if (!found) {
res.push(0);
}
}
return res;
}
const arr = [12, -1, -7, 8, -15, 30, 16, 28];
const k = 3;
const res = firstNegInt(arr, k);
console.log(res);
Output[-1, -1, -7, -15, -15, 0]
Time Complexity : The outer loop runs n−k+1 times, and for each iteration, the inner loop runs k times. This gives us a time complexity of O((n−k+1)×k), which simplifies to O(n*k) when k is much smaller than n. If k is close to n, the complexity becomes O(k).
Auxiliary Space: O(1) as it is using constant space for variables
[Better Approach] Sliding Window with Deque technique - O(n) time and O(k) space
We create a Dequeue, dq 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 dq to contain useful elements of current window and these useful elements are all negative integers. For a particular window, if dq is not empty then the element at front of the dq 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.
C++
#include <iostream>
#include <deque>
#include <vector>
using namespace std;
// Function to find the first negative integer
// in every window of size k
vector<int> firstNegInt(vector<int>& arr, int k) {
deque<int> dq;
vector<int> res;
int n = arr.size();
// Process the first window of size k
for (int i = 0; i < k; i++) {
if (arr[i] < 0) {
dq.push_back(i);
}
}
// Process the rest of the elements
for (int i = k; i < n; i++) {
// If there is any negative number in the window, add it to the result
if (!dq.empty()) {
res.push_back(arr[dq.front()]);
} else {
res.push_back(0);
}
// Remove elements which are out of this window
while (!dq.empty() && dq.front() <= i - k) {
dq.pop_front();
}
// Add the current element if it is negative
if (arr[i] < 0) {
dq.push_back(i);
}
}
// For the last window, process it separately
if (!dq.empty()) {
res.push_back(arr[dq.front()]);
} else {
res.push_back(0);
}
return res;
}
int main() {
vector<int> arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
// Get the result from the function
vector<int> result = firstNegInt(arr, k);
// Print the result in the required format
cout << "[";
for (size_t i = 0; i < result.size(); i++) {
cout << result[i];
if (i != result.size() - 1)
cout << ", ";
}
cout << "]" << endl;
return 0;
}
Java
import java.util.*;
public class GfG {
public static int[] firstNegInt(int[] arr, int k) {
Deque<Integer> dq = new LinkedList<>();
List<Integer> res = new ArrayList<>();
int n = arr.length;
// Process first k (or first window) elements
for (int i = 0; i < k; i++)
if (arr[i] < 0)
dq.addLast(i);
// Process rest of the elements, i.e.,
// from arr[k] to arr[n-1]
for (int i = k; i < n; i++) {
if (!dq.isEmpty())
res.add(arr[dq.peekFirst()]);
else
res.add(0);
// Remove the elements which are out of
// this window
while (!dq.isEmpty() && dq.peekFirst() < (i - k + 1))
dq.pollFirst();
// Add current element at the rear
// of dq if it is a negative integer
if (arr[i] < 0)
dq.addLast(i);
}
// Print the first negative integer of
// the last window
if (!dq.isEmpty())
res.add(arr[dq.peekFirst()]);
else
res.add(0);
return res.stream().mapToInt(i -> i).toArray();
}
public static void main(String[] args) {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
int[] result = firstNegInt(arr, k);
// Print the result in the required format
System.out.print(Arrays.toString(result));
}
}
Python
# Function to find the first negative integer
# in every window of size k
def firstNegInt(arr, k):
from collections import deque
dq = deque()
res = []
n = len(arr)
# Process first k (or first window) elements
for i in range(k):
if arr[i] < 0:
dq.append(i)
# Process rest of the elements, i.e.,
# from arr[k] to arr[n-1]
for i in range(k, n):
if dq:
res.append(arr[dq[0]])
else:
res.append(0)
# Remove the elements which are out of
# this window
while dq and dq[0] < (i - k + 1):
dq.popleft()
# Add current element at the rear
# of dq if it is a negative integer
if arr[i] < 0:
dq.append(i)
# Print the first negative integer of
# the last window
if dq:
res.append(arr[dq[0]])
else:
res.append(0)
return res
# Driver program to test the above function
arr = [12, -1, -7, 8, -15, 30, 16, 28]
k = 3
result = firstNegInt(arr, k)
# Print the result in the required format
print(result)
C#
using System;
using System.Collections.Generic;
class GfG {
public static int[] FirstNegInt(int[] arr, int k) {
Queue<int> dq = new Queue<int>();
List<int> res = new List<int>();
int n = arr.Length;
// Process first k (or first window) elements
for (int i = 0; i < k; i++)
if (arr[i] < 0)
dq.Enqueue(i);
// Process rest of the elements, i.e.,
// from arr[k] to arr[n-1]
for (int i = k; i < n; i++) {
if (dq.Count > 0)
res.Add(arr[dq.Peek()]);
else
res.Add(0);
// Remove the elements which are out of
// this window
while (dq.Count > 0 && dq.Peek() < (i - k + 1))
dq.Dequeue();
// Add current element at the rear
// of dq if it is a negative integer
if (arr[i] < 0)
dq.Enqueue(i);
}
// Print the first negative integer of
// the last window
if (dq.Count > 0)
res.Add(arr[dq.Peek()]);
else
res.Add(0);
return res.ToArray();
}
static void Main() {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
int[] result = FirstNegInt(arr, k);
// Print the result in the required format
Console.WriteLine("[" + string.Join(", ", result) + "]");
}
}
JavaScript
// Function to find the first negative integer
// in every window of size k
function firstNegInt(arr, k) {
let dq = [];
let res = [];
let n = arr.length;
// Process first k (or first window) elements
for (let i = 0; i < k; i++) {
if (arr[i] < 0) {
dq.push(i);
}
}
// Process rest of the elements, i.e.,
// from arr[k] to arr[n-1]
for (let i = k; i < n; i++) {
if (dq.length > 0) {
res.push(arr[dq[0]]);
} else {
res.push(0);
}
// Remove the elements which are out of
// this window
while (dq.length > 0 && dq[0] < (i - k + 1)) {
dq.shift();
}
// Add current element at the rear
// of dq if it is a negative integer
if (arr[i] < 0) {
dq.push(i);
}
}
// Print the first negative integer of
// the last window
if (dq.length > 0) {
res.push(arr[dq[0]]);
} else {
res.push(0);
}
return res;
}
// Driver program to test the above function
let arr = [12, -1, -7, 8, -15, 30, 16, 28];
let k = 3;
let result = firstNegInt(arr, k);
// Print the result in the required format
console.log(JSON.stringify(result));
Output[-1, -1, -7, -15, -15, 0]
[Expected Approach] Sliding Window with Index Tracking - O(n) time and O(1) space
This approach uses a sliding window technique to find the first negative integer in each window of size k
. It keeps track of the index of the first negative integer within the current window and skips over positive elements or those that have moved out of the window. This ensures that the first negative element is efficiently identified for each window as it slides.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> firstNegInt(vector<int>& arr, int k) {
int fstNegIdx = 0;
vector<int> res;
int n = arr.size(); // Use size() for vectors
for (int i = k - 1; i < n; i++) {
// Skip out of window and positive elements
while ((fstNegIdx < i) && (fstNegIdx <= i - k || arr[fstNegIdx] >= 0)) {
fstNegIdx++;
}
// Check if a negative element is found,
// otherwise use 0
if (fstNegIdx < n && arr[fstNegIdx] < 0) {
res.push_back(arr[fstNegIdx]);
}
else {
res.push_back(0);
}
}
return res;
}
int main() {
vector<int> arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
vector<int> res = firstNegInt(arr, k);
cout << "[";
for (size_t i = 0; i < res.size(); i++) {
cout << res[i];
if (i != res.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<Integer> firstNegInt(int[] arr, int k) {
int fstNegIdx = 0;
List<Integer> res = new ArrayList<>();
int n = arr.length;
for (int i = k - 1; i < n; i++) {
// Skip out of window and positive elements
while (fstNegIdx < i && (fstNegIdx <= i - k || arr[fstNegIdx] >= 0)) {
fstNegIdx++;
}
// Check if a negative element is found,
// otherwise use 0
if (fstNegIdx < n && arr[fstNegIdx] < 0) {
res.add(arr[fstNegIdx]);
} else {
res.add(0);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
List<Integer> res = firstNegInt(arr, k);
System.out.println(res);
}
}
Python
def first_neg_int(arr, k):
fst_neg_idx = 0
res = []
n = len(arr)
for i in range(k - 1, n):
# Skip out of window and positive elements
while fst_neg_idx < i and (fst_neg_idx <= i - k or arr[fst_neg_idx] >= 0):
fst_neg_idx += 1
# Check if a negative element is found,
# otherwise use 0
if fst_neg_idx < n and arr[fst_neg_idx] < 0:
res.append(arr[fst_neg_idx])
else:
res.append(0)
return res
# Driver code
arr = [12, -1, -7, 8, -15, 30, 16, 28]
k = 3
res = first_neg_int(arr, k)
print(res)
C#
using System;
using System.Collections.Generic;
class GfG {
public static List<int> FirstNegInt(int[] arr, int k) {
int fstNegIdx = 0;
List<int> res = new List<int>();
int n = arr.Length;
for (int i = k - 1; i < n; i++) {
// Skip out of window and positive elements
while (fstNegIdx < i && (fstNegIdx <= i - k || arr[fstNegIdx] >= 0)) {
fstNegIdx++;
}
// Check if a negative element is found,
// otherwise use 0
if (fstNegIdx < n && arr[fstNegIdx] < 0) {
res.Add(arr[fstNegIdx]);
} else {
res.Add(0);
}
}
return res;
}
static void Main() {
int[] arr = {12, -1, -7, 8, -15, 30, 16, 28};
int k = 3;
List<int> res = FirstNegInt(arr, k);
Console.WriteLine(string.Join(", ", res));
}
}
JavaScript
function firstNegInt(arr, k) {
let fstNegIdx = 0;
let res = [];
let n = arr.length;
for (let i = k - 1; i < n; i++) {
// Skip out of window and positive elements
while (fstNegIdx < i && (fstNegIdx <= i - k || arr[fstNegIdx] >= 0)) {
fstNegIdx++;
}
// Check if a negative element is found,
// otherwise use 0
if (fstNegIdx < n && arr[fstNegIdx] < 0) {
res.push(arr[fstNegIdx]);
} else {
res.push(0);
}
}
return res;
}
// Driver code
let arr = [12, -1, -7, 8, -15, 30, 16, 28];
let k = 3;
let res = firstNegInt(arr, k);
console.log(res);
Output[-1, -1, -7, -15, -15, 0]
Similar Reads
Count Distinct Elements In Every Window of Size K Given an array arr[] of size n and an integer k, return the count of distinct numbers in all windows of size k. Examples: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4Output: [3, 4, 4, 3]Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3. Second window is [2, 1, 3, 4] count of d
10 min read
Maximum of minimums of every window size in a given array Given an integer array arr[] of size n, the task is to find the maximum of the minimums for every window size in the given array, where the window size ranges from 1 to n.Example:Input: arr[] = [10, 20, 30]Output: [30, 20, 10]Explanation: First element in output indicates maximum of minimums of all
14 min read
Birthday Gift: Counting integer Arrays with interesting properties Your birthday is coming soon and one of your friends, Alex, is thinking about a gift for you. He knows that you really like integer arrays with interesting properties. He selected two numbers, N and K, and decided to write down on paper all integer arrays of length K (in form a[1], a[2], â¦, a[K]), w
6 min read
Check whether a number can be represented as sum of K distinct positive integers Given two integers N and K, the task is to check whether N can be represented as sum of K distinct positive integers. Examples: Input: N = 12, K = 4 Output: Yes N = 1 + 2 + 4 + 5 = 12 (12 as sum of 4 distinct integers) Input: N = 8, K = 4 Output: No Recommended: Please try your approach on {IDE} fir
10 min read
Minimum window size containing atleast P primes in every window of given range Given three integers X, Y and P, the task is to find the minimum window size K such that every window in the range [X, Y] of this size have atleast P prime numbers.Examples: Input: X = 2, Y = 8, P = 2 Output: 4 Explanation: In the range [2, 8], window size of 4 contains atleast 2 primes in each wind
15+ min read
Generate first K multiples of N using Bitwise operators Given an integer N, the task is to print the first K multiples of N using Bitwise Operators. Examples: Input: N = 16, K = 7 Output: 16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112Input: N = 7, K = 10 Output: 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7
5 min read
Count of elements in an Array whose set bits are in a multiple of K Given an array arr[] of N elements and an integer K, the task is to count all the elements whose number of set bits is a multiple of K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 2 Explanation: Two numbers whose setbits count is multiple of 2 are {3, 5}.Input: arr[] = {10, 20, 30, 40}, K
9 min read
Largest integers with sum of setbits at most K Given an array of integer nums[] and a positive integer K, the task is to find the maximum number of integers that can be selected from the array such that the sum of the number of 1s in their binary representation is at most K. Examples: Input: nums[] = [3, 9, 4, 6], K = 3Output: 2Explanation: The
7 min read
Sliding Window Problems | Identify, Solve and Interview Questions When we are dealing with problems that require checking answers of some ranges in an array, the Sliding window algorithm can be a very powerful technique. What are Sliding Window Problems?Sliding window problems are computational problems in which a fixed/variable-size window is moved through a data
4 min read