How to count the occurence of each element in map data structure

plz explain the logic behind this… like for 2 rows
1 3
2 4
1 4
i want to count the occurence of each element in both the rows

1 Like

For C++

map<int,int>m1,m2; 
for(int i=0;i<3;++i){
    int x,y; cin >> x >> y; 
    m1[x]++; m2[y]++;
}
8 Likes

Thanks

For Java

int[][] input = new int[rows][2]; //Input is stored here
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<rows;i++){
     map.put(input[i][0] , map.getOrDefault(input[i][0] , 0)+1);
     map.put(input[i][1] , map.getOrDefault(input[i][1] , 0)+1);
}

Otherwise you can simply create an array of size equal to maximum number in the input. This will only work if max number in the input <= 10^6 since an array can have a max size of 10^6.

    int max = getMax(input); //Stores maximum element present in the input
    int[] numCount = new int[max+1]; //Create an array of size 'max'
    for(int i=0;i<rows;i++){
          for(int j=0;j<input[i].length;j++){
              numCount[input[i][j]]++;
          }
    }