Problem Statement:
You are given an array and a integer K.
You need to find the first -ve integer for each window of size k.
return 0, if there are no 0ve integers.
Example:
Input: arr[] = [-1, 2, 3, -4, 5] k = 2
Output: [-1, 0, -4, -4]
Explanation: First negative integer for each window size of 2
[-1, 2] = -1
[2, 3] = 0
[3, -4] = -4
[-4, 5] = -4
Solution 1: Sliding window
We will use sliding window in this solution.
We will take a temp variable to check the first -ve integer of the current window and print it.
Then slide the window and update the results accordingly.
Time Complexity: O(1)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
using namespace std;
void solution(vector<int>& arr, int k)
{
int n = arr.size();
bool isNeg;
for (int i = 0; i<(n-k+1); i++)
{
isNeg = false;
for (int j = 0; j<k; j++)
{
if (arr[i+j] < 0)
{
cout<<arr[i+j]<<" ";
isNeg = true;
break;
}
}
if (!isNeg)
cout<<"0 ";
}
}
int main()
{
vector<int> arr = {-1, 2, 3, -4, 5};
int k = 2;
solution(arr, k);
return 0;
}
Output
-1 0 -4 -4