C++ | Map | Easy to Understand
Approach\n\nWe first create a map that maps each element in the matrix to its row and column position. Then, for each element in the array, we look up its row a
# Approach\n\nWe first create a map that maps each element in the matrix to its row and column position. Then, for each element in the array, we look up its row and column position in the map and increments the count of elements in that row and column.\n\nIf the count of elements in any row or column reaches the size of the matrix, it means that all the elements needed to complete that row or column have been found. In that case, return the index of the current element in the list.\n\nIf no element completes a row or column, the return -1.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        int m=mat.size();\n        int n=mat[0].size();\n\n        unordered_map<int, int> rowcount, colcount; \n        unordered_map<int,pair<int,int>>mp;\n\n        for(int i=0;i<m;++i){\n            for(int j=0;j<n;++j){\n                mp[mat[i][j]]={i,j}; //store the coordinates of each number in the matrix\n            }\n        }\n\n        for(int i=0;i<arr.size();++i){\n            int row=mp[arr[i]].first;\n            int col=mp[arr[i]].second;\n            \n            // increment the row and column count for each occurrence\n            ++rowcount[row];\n            ++colcount[col];\n            \n            // if any row or column has all the numbers, return the current index          \n            if(rowcount[row]==n || colcount[col]==m) return i;\n        }      \n        return -1;\n    }\n};\n```
['C++']