Minimum number of steps required to place all 1 s at a single index | Function to prlet minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith index ; Count number of 1 s present till i - th index ; Initialize count ; Traverse the array in backward direction ; Steps needed to store all 1 s to the right of i at current index ; Count number of 1 s present after i - th index ; Print the number of steps required ; Driver code
function minsteps ( A ) { let n = A . length ; let left = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let right = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let res = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let count = A [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { left [ i ] = left [ i - 1 ] + count ; count += A [ i ] ; } count = A [ n - 1 ] ; for ( let i = n - 2 ; i >= 0 ; i -- ) { right [ i ] = right [ i + 1 ] + count ; count += A [ i ] ; } for ( let i = 0 ; i < n ; i ++ ) { res [ i ] = left [ i ] + right [ i ] ; document . write ( res [ i ] + " " ) ; } document . write ( " " ) ; } let A = [ 1 , 0 , 1 , 0 ] ; minsteps ( A ) ;