Count the number of pop operations on stack to get each element of the array | Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equal to num ; Pop the top ie . equal to num ; Print the number of elements popped . ; Driver code
function countEle ( s , a , N ) { var mp = new Map ( ) ; for ( var i = 0 ; i < N ; ++ i ) { var num = a [ i ] ; if ( mp . has ( num ) ) document . write ( " " ) ; else { var cnt = 0 ; while ( s [ s . length - 1 ] != num ) { mp . set ( s [ s . length - 1 ] , true ) ; s . pop ( ) ; cnt ++ ; } s . pop ( ) ; cnt ++ ; document . write ( cnt + " " ) ; } } } var N = 5 ; var s = [ ] ; s . push ( 1 ) ; s . push ( 2 ) ; s . push ( 3 ) ; s . push ( 4 ) ; s . push ( 6 ) ; var a = [ 6 , 3 , 4 , 1 , 2 ] ; countEle ( s , a , N ) ;