C++ | Using Only Single Map | Explained | Easy to Understand
C++ Code\n\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        \n        int n = size(mat), m = size(m
**C++ Code**\n```\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        \n        int n = size(mat), m = size(mat[0]), res = m*n;\n        \n        unordered_map<int,int> map;\n        \n        for(int i = 0; i < m*n; i++)map[arr[i]] = i;\n        \n        for(int i = 0; i < n; i++) {\n            int maxIdx = 0;\n            \n            for(int j = 0; j < m; j++) {\n                maxIdx = max(maxIdx, map[mat[i][j]]);\n            }\n            \n            res = min(res,maxIdx);\n        }\n        \n        for(int i = 0; i < m; i++) {\n            int maxIdx = 0;\n            \n            for(int j = 0; j < n; j++) {\n                maxIdx = max(maxIdx, map[mat[j][i]]);\n            }\n            \n            res = min(res,maxIdx);\n        }\n        \n        return res;\n        \n    }\n};\n```\n\n**Explanation**\n\n* unordered_map<int,int> map; - Here used to mark the order of arr items\n* First loop iterates by row, to identify by each row the index of last marked arr item. Then get the min, which row marked(finished) first:\n\n```\nfor(int i = 0; i < n; i++) {\n            int maxIdx = 0;\n            \n            for(int j = 0; j < m; j++) {\n                maxIdx = max(maxIdx, map[mat[i][j]]);\n            }\n            \n            res = min(res,maxIdx);\n}\n```\n* Second loop iterates by column and makes the same logic as first loop described above.\n\n* Let\'s test in second example of the problem:\n```Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] Output: 3```\n\n* After mark the order of arr in map, we can draw second matrix that shows the mark position by arr:\n\n```\n[5,0,6],\n[4,3,7],\n[1,2,8]\n```\n\n* First loop iteration by row:\n\n```\n[5,0,6], // maxIdx = 6\n[4,3,7], // maxIdx = 7\n[1,2,8] // maxIdx = 8\n\nmin of these is `6`, we can see by row first finished first row, by arr item index `6`\n```\n\n* Second loop iteration by column:\n```\n[5,0,6], \n[4,3,7], \n[1,2,8] \n\nMax by col:\n5 3 8\n```\n\n* min of these(5,3,8) is 3, we can see by column first finished second column by arr item index 3. If we compare which one first finished by row or column, the answer is by column because arr value by index 3 becomes earlier than index 6\n\n*Thank you @Yerkon for explaining the code*
['Hash Table', 'C', 'C++']