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