First negative integer in every window of size k | Python3 implementation to find the first negative integer in every window of size k import deque ( ) from collections ; function to find the first negative integer in every window of size k ; A Double Ended Queue , Di that will store indexes of useful array elements for the current window of size k . The useful elements are all negative integers . ; Process first k ( or first window ) elements of array ; Add current element at the rear of Di if it is a negative integer ; Process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; if the window does not have a negative integer ; if Di is not empty then the element at the front of the queue is the first negative integer of the previous window ; Remove the elements which are out of this window ; Remove from front of queue ; Add current element at the rear of Di if it is a negative integer ; Print the first negative integer of last window ; Driver Code
from collections import deque NEW_LINE def printFirstNegativeInteger ( arr , n , k ) : NEW_LINE INDENT Di = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT Di . append ( i ) ; NEW_LINE DEDENT DEDENT for i in range ( k , n ) : NEW_LINE INDENT if ( not Di ) : NEW_LINE INDENT print ( 0 , end = ' ▁ ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ Di [ 0 ] ] , end = ' ▁ ' ) ; NEW_LINE DEDENT while Di and Di [ 0 ] <= ( i - k ) : NEW_LINE INDENT Di . popleft ( ) NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT Di . append ( i ) ; NEW_LINE DEDENT DEDENT if not Di : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ Di [ 0 ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printFirstNegativeInteger ( arr , n , k ) ; NEW_LINE DEDENT