Store frequency of elements in matrix
for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mp . containsKey ( arr [ i ] [ j ] ) ) mp . put ( arr [ i ] [ j ] , mp . get ( arr [ i ] [ j ] ) + 1 ) ; else mp . put ( arr [ i ] [ j ] , 1 ) ; } }