Count the number of pop operations on stack to get each element of the array | C ++ program to implement above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countEle ( stack < int > & s , int a [ ] , int N ) { unordered_map < int , bool > mp ; for ( int i = 0 ; i < N ; ++ i ) { int num = a [ i ] ; if ( mp . find ( num ) != mp . end ( ) ) cout << "0 ▁ " ; else { int cnt = 0 ; while ( s . top ( ) != num ) { mp [ s . top ( ) ] = true ; s . pop ( ) ; cnt ++ ; } s . pop ( ) ; cnt ++ ; cout << cnt << " ▁ " ; } } } int main ( ) { int N = 5 ; stack < int > s ; s . push ( 1 ) ; s . push ( 2 ) ; s . push ( 3 ) ; s . push ( 4 ) ; s . push ( 6 ) ; int a [ ] = { 6 , 3 , 4 , 1 , 2 } ; countEle ( s , a , N ) ; return 0 ; }