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
Basics & Prerequisites
Data Structures
Array IntroductionArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
13 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem