Iterate form last to current position and find where the task will happen next .
vector < int > d ( m + 1 , 0 ) ; for ( int i = m ; i > pos ; i -- ) { if ( isRunning [ arr [ i ] ] ) d [ arr [ i ] ] = i ; }