Given an integer array a and an integer window size k, return the first negative integer in every contiguous subarray (window) of size k. If a window contains no negative numbers, return 0 for that window.
For each starting index i, scan the next k elements to find the first negative number. This directly follows the problem statement but repeats work across overlapping windows.
classSolution {
public: vector<longlong> firstNegativeInWindow(const vector<longlong>& a, int k) {
int n = a.size();
vector<longlong> ans;
if (k > n) return ans;
for (int i =0; i <= n - k; ++i) {
longlong first =0;
for (int j = i; j < i + k; ++j) {
if (a[j] <0) { first = a[j]; break; }
}
ans.push_back(first);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
packagemain// firstNegativeInWindow returns first negative number for each window of size k.funcfirstNegativeInWindow(a []int, kint) []int {
n:= len(a)
ifk > n { return []int{} }
ans:= make([]int, 0, n-k+1)
fori:=0; i<=n-k; i++ {
first:=0forj:=i; j < i+k; j++ {
ifa[j] < 0 { first = a[j]; break }
}
ans = append(ans, first)
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publiclong[]firstNegativeInWindow(long[] a, int k) {
int n = a.length;
if (k > n) returnnewlong[0];
long[] ans =newlong[n - k + 1];
int idx = 0;
for (int i = 0; i <= n - k; i++) {
long first = 0;
for (int j = i; j < i + k; j++) {
if (a[j]< 0) { first = a[j]; break; }
}
ans[idx++]= first;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deffirst_negative_in_window(self, a: list[int], k: int) -> list[int]:
n = len(a)
if k > n:
return []
ans: list[int] = []
for i in range(0, n - k +1):
first =0for j in range(i, i + k):
if a[j] <0:
first = a[j]
break ans.append(first)
return ans
Windows overlap heavily; we can avoid re-scanning the overlapping portion by maintaining the negative elements seen so far in a FIFO structure. Store indices of negative elements so we can efficiently check whether the stored negative is still inside the current window.
#include<deque>classSolution {
public: vector<int> firstNegativeInWindow(const vector<int>& a, int k) {
int n = a.size();
vector<int> ans;
if (k > n) return ans;
deque<int> q; // store indices of negative numbers
int start =0;
for (int end =0; end < n; ++end) {
if (a[end] <0) q.push_back(end);
if (end - start +1== k) {
if (q.empty()) ans.push_back(0);
else ans.push_back(a[q.front()]);
if (!q.empty() && q.front() == start) q.pop_front();
++start;
}
}
return ans;
}
};
from collections import deque
classSolution:
deffirst_negative_in_window(self, a: list[int], k: int) -> list[int]:
n = len(a)
if k > n:
return []
ans: list[int] = []
q: deque[int] = deque() # indices of negative numbers start =0for end in range(n):
if a[end] <0:
q.append(end)
if end - start +1== k:
ifnot q:
ans.append(0)
else:
ans.append(a[q[0]])
if q and q[0] == start:
q.popleft()
start +=1return ans