First negative integer in every window of size k | Practice | GeeksforGeeks

Given an array A[] of size N and a positive integer K, find the first negative integer for each and every window(contiguous subarray) of size K.
 
Example 1:
Input : 
N = 5
A[] = {-8, 2, 3, -6, 10}
K = 2
Output : 
-8 0 -6 -6
Explanation :
First negative integer for each window of size k
{-8, 2} = -8
{2, 3} = 0 (does not contain a negative integer)
{3, -6} = -6
{-6, 10} = -6
Input : 
N = 8
A[] = {12, -1, -7, 8, -15, 30, 16, 28}
K = 3
Output :
-1 -1 -7 -15 -15 0 
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function printFirstNegativeInteger() which takes the array A[], its size N and an integer K as inputs and returns the first negative number in every window of size K starting from the first till the end. If a window does not contain a negative integer , then return 0 for that window.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(K)

Constraints:
1 <= N <= 105
-105 <= A[i] <= 105
1 <= K <= N
0
purubhargava01120 hours ago
vector<long long> printFirstNegativeInteger(long long int input[],
                                            long long int n, long long int k) {
                                                
   long long  j = 0 ; long long i = 0 ; 
   queue<long long> q ; 
   vector<long long> ans ; 
   
   
   while(j < n){
       if(j - i + 1 == k ){
           if(input[j] < 0){
               q.push(j) ; 
           }
           if(q.size() and !(q.front() >= i and q.front() <= j)){
               q.pop() ; 
           }
           if(q.size() == 0){
               ans.push_back(0) ; 
           }
           if(q.size() and q.front() >= i and q.front() <= j){
               ans.push_back(input[q.front()]) ; 
           }
           i += 1 ;
       }
       else {
           if(input[j] < 0 ){
               q.push(j) ;
           }
       }
       j += 1 ;
   }
   return ans ; 
}
0
utkarshrdce2 days ago


/*
    negIdx stores the index of the first element of the window which was just previously processed
    as soon as you arrive at this element, update negIdx to i (the current index) if the element is negative
    check if negIdx lies in the window of size k, and fill the answer
*/
vector<long long> printFirstNegativeInteger(long long int A[], long long int N, long long int K) {

    vector<long long> ans;
    int negIdx = N;
    int j = N - 1;
    for (j = N - 1; j > N - K; j--) {
        if (A[j] < 0) negIdx = j;
    }


    // as soon as you arrive at this element, update negIdx if the element is negative
    while (j >= 0) {
        if (A[j] < 0) negIdx = j;
        if (j + K - 1 >= negIdx) ans.push_back(A[negIdx]);
        else ans.push_back(0);
        j--;
    }


    reverse(ans.begin(), ans.end());
    return ans;
}
0
yashpaneliya
This comment was deleted.
+1
jainatishay0725 days ago
Python Solution 
If You like that please vote upward
def printFirstNegativeInteger( arr, n, k):
    res=[]
    q=[]
    i,j=0,0
    while j<n:
        if arr[j]<0:
            q.append(arr[j])
        if j-i+1<k:
            j+=1
        elif j-i+1==k:
            if len(q)==0:
                res.append(0)
            else:
                res.append(q[0])
                if arr[i]==q[0]:
                    q.pop(0)
            i+=1
            j+=1
    return res
0
thakuraditya6216 days ago
public long[] printFirstNegativeInteger(long A[], int N, int K)
    {
        // O((n-k+1)*k) or
        // O(NK)
        boolean flag;
        long[] ans = new long[N-K+1];
        int l = 0;
        for(int i = 0; i < (N-K + 1); i++){
            flag = false;
            
            for(int j = 0; j < K ; j++){
                if(A[i+j] < 0){
                    ans[l++] = A[i+j];
                    flag = true;
                    break;
                }
            }
            
            if(!flag){
                ans[l++] = 0;
            }
        }
        return ans;
        
    // -----------------------------------------------------------------------------------    
        // nNext Approch Using Queue
        // O(N) and O(K)
        
        Queue<Long> q=new LinkedList<>();
      long[]ans=new long[N-K+1];
      for(int i=0;i<K-1;i++){
          q.add(A[i]);
      }
      for(int i=K-1,j=0;i<N && j<N-K+1;i++,j++){
          if(q.size()==K){
              q.remove();
              q.add(A[i]);
          }else if(q.size()<K)
                q.add(A[i]);
                
          while(!q.isEmpty() && q.peek()>=0){
              q.remove();
          }
           
          if(q.isEmpty())
                ans[j]=0;
          else 
                ans[j] = q.peek();
      }
      return ans;
    
    //-------------------------------------------------------------------------
    
    // O(N) and O(1)
    
    int nIdx = 0;
    long nEmnt ;
    long []ans = new long [N-K+1];
    int j=0;
    for(int i = K-1; i < N; i++){
        
        while((nIdx < i) && (nIdx <= i - K || A[nIdx] > 0) ){
            nIdx++;
        }
        
         // Check if a negative element is
        // found, otherwise use 0
        if (A[nIdx] < 0)
        {
            nEmnt = A[nIdx];
            ans[j++] = nEmnt;
        }
        else
        {
            nEmnt = 0;
            ans[j++] = nEmnt;
        }
    }
            return ans;

    
    }
+3
sidvas581 week ago
//Learnt from Aditya Verma's vid
vector<long long int> v;   list<long long int> l;   long long int i=0,j=0;   while(j<n)   {       if(arr[j]<0)       l.push_back(arr[j]);       if(j-i+1<k)       j++;       else if(j-i+1==k)       {           if(l.size()==0)           v.push_back(0);           else           {               v.push_back(l.front());               if(arr[i]==l.front())               l.pop_front();           }           i++;           j++;       }   }   return v;
+2
kunalwalia20011 week ago
C++ Solution With Complexity O(n) and O(1) without extra space
vector<long long> printFirstNegativeInteger(long long int A[],                                            long long int N, long long int K) {              int firstNegativeIndex = 0;        int  firstNegativeElement;        vector<long long int> ans;       // skip out of window and +ve elements       for(int i = K-1;i<N;i++){            while((firstNegativeIndex < i) && (firstNegativeIndex <= i-K || A[firstNegativeIndex] > 0)){                firstNegativeIndex++;            }            // check if -ve element is found or not            if(A[firstNegativeIndex] < 0){                firstNegativeElement = A[firstNegativeIndex];                ans.push_back(firstNegativeElement);            }else            {                ans.push_back(0);            }          }       return ans;             }
0
shrustis1762 weeks ago
C++ solution using Sliding Window
 
vector<long long> printFirstNegativeInteger(long long int A[],                                            long long int N, long long int K) {                                                       queue<long long>q;         vector<long long>v;       int i=0,j=0;       while(j<N)       {           if(A[j] < 0)               q.push(A[j]);           if(j-i+1 < K)               j++;           else if(j-i+1 == K)           {               if(q.empty())                   v.push_back(0);               else               {                   v.push_back(q.front());                   if(A[i] == q.front())                       q.pop();               }               i++;               j++;           }       }       return v;}
+1
anshjaiswal202 weeks ago
Easy Java Solution
class Compute {      public long[] printFirstNegativeInteger(long a[], int n, int k)   {       Queue<Long> q=new LinkedList<>();       long[]ans=new long[n-k+1];       for(int i=0;i<k-1;i++){           q.add(a[i]);       }       for(int i=k-1,j=0;i<n && j<n-k+1;i++,j++){           if(q.size()==k){               q.remove();               q.add(a[i]);           }else if(q.size()<k)q.add(a[i]);           while(!q.isEmpty() && q.peek()>=0){               q.remove();           }           if(q.isEmpty())ans[j]=0;           else ans[j]=q.peek();       }       return ans;   }}
0
pankajsingh852013 weeks ago
vector<long long> printFirstNegativeInteger(long long int A[],
                                             long long int N, long long int K) {
           
           vector<long long> ans;
           queue<int> q;
           for(int i=0;i<K;i++)
           {
               if(A[i]<0)
               {
                   q.push(i);
               }
           }
           if(q.empty()) ans.push_back(0);
           else ans.push_back(A[q.front()]);       
           for(int i=1;i<=N-K;i++)
           {
               if(A[K+i-1]<0) q.push(K+i-1);
               while(!q.empty())
               {
                   int j = q.front();
                   if(j>=i and j<=K+i-1)
                   {
                       ans.push_back(A[j]);
                       break;
                   }
                   else
                   {
                       q.pop();
                   }
               }
               if(q.empty())ans.push_back(0);
           }
           
           return ans;
 }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.