What is First Negative Integer
For every window of length k, print the first negative value in that window. If the window has no negative, print 0.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index enters and leaves the queue once. |
| Space | O(k) | At most the negatives inside one window. |
Implementation
from collections import deque
def solve(self, nums, k):
dq, ans = deque(), []
for i, val in enumerate(nums):
if dq and dq[0] <= i-k: dq.popleft()
if val < 0: dq.append(i)
if i >= k-1:
ans.append(nums[dq[0]] if dq else 0)
return ans