Brute Force to Optimal | Easy to Understand
\n//Brute Force :-  O(n^2) (will give TLE)\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        int m=m
```\n//Brute Force :-  O(n^2) (will give TLE)\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        int m=mat.size(), n=mat[0].size(), size=arr.size(), idx=0;\n        unordered_set<int>st;\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};\n                }\n         }\n        while(idx < size) {\n            st.insert(arr[idx]);\n            auto it = mp.find(arr[idx]);\n            int i=(it->second).first, j=(it->second).second;\n            bool valid1=true,valid2=true;\n                \n            for(int col=0;col<n;col++) {\n                if(st.find(mat[i][col]) == st.end()) {\n                     valid1=false;\n                    break;\n                }\n\n            }\n            \n            for(int row=0;row<m;row++) {\n                if(st.find(mat[row][j]) == st.end()) {\n                    valid2=false;\n                    break;\n                }\n\n            }\n            if(valid2 || valid1)return idx;\n\n                idx++;\n        }\n        return -1;\n    }\n};\n\n//Optimal :-  O(m*n)\n\nclass Solution {\npublic:\n    int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {\n        unordered_map<int,int>mp;\n        int maxIdx = 0, m = mat.size(), n = mat[0].size(), res = INT_MAX;\n        for(int i=0;i<arr.size();i++)\n            mp[arr[i]]=i;\n        \n        for(int i=0;i<m;i++) {\n            maxIdx = 0;\n            for(int j=0;j<n;j++) {\n                maxIdx = max(maxIdx, mp[mat[i][j]]);\n            }\n            res = min(res, maxIdx);\n        }\n         for(int i=0;i<n;i++) {\n            maxIdx = 0;\n            for(int j=0;j<m;j++) {\n                maxIdx = max(maxIdx, mp[mat[j][i]]);\n            }\n            res = min(res, maxIdx);\n        }\n        return res;\n    }\n};\n```
['C', 'C++']