The first negative number in every window
MediumStuck?
Show a hintHide the hint
Keep a queue of the positions of negatives inside the window. Drop the front once it falls out on the left, and the front is the answer.
The ideas behind this problem
Next in this lesson
Shortest stretch that reaches the targetGiven a list of numbers and a size k, report the first negative number in each window of k consecutive numbers. If a window has no negative number, report 0 for it.
Worked example#
For [12, -1, -7, 8, -15, 30, 16, 28] with k = 3:
| window | numbers | first negative |
|---|---|---|
| 0 to 2 | 12, -1, -7 | -1 |
| 1 to 3 | -1, -7, 8 | -1 |
| 2 to 4 | -7, 8, -15 | -7 |
| 3 to 5 | 8, -15, 30 | -15 |
| 4 to 6 | -15, 30, 16 | -15 |
| 5 to 7 | 30, 16, 28 | none, so 0 |
So the answer is [-1, -1, -7, -15, -15, 0].
The idea#
Scanning each window for its first negative is n times k again. The thing to notice is what carries over: the first negative of the previous window is usually still the first negative of this one.
So keep a queue of the positions of negative numbers currently inside the window, in the order they appear. Then:
- when the window moves right, any new number that is negative joins the back of the queue;
- anything at the front that has now fallen out of the window on the left is removed;
- the front of the queue, if there is one, is the answer.
A queue rather than a stack, because you want the earliest negative still in range, not the most recent. That is the whole reason the structure differs from the monotonic stack problems, and it is worth sitting with: the question decides the end you take things from.
Every position joins the queue at most once and leaves at most once, so this is one pass.
Constraints#
1 <= k <= n <= 100000-1000000 <= nums[i] <= 1000000
Input
nums is a count then that many integers. k is a single integer on the next line.
Output
A count is not printed. Print one answer per window, separated by spaces.
Examples
Input
8 12 -1 -7 8 -15 30 16 28 3
Output
-1 -1 -7 -15 -15 0
The last window holds no negative number, so it reports 0.
Input
5 -8 2 3 -6 10 2
Output
-8 0 -6 -6
Each window of two is checked in turn.
Input
4 1 2 3 4 2
Output
0 0 0
Nothing is negative, so every window reports 0.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.