2133. Check if Every Row and Column Contains All Numbers

class Solution {
public:
    bool checkValid(vector<vector<int>>& matrix)
    {
        int n = matrix.size();
        unordered_set<int> rowSet, colSet;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (rowSet.count(matrix[i][j]))
                {
                    return false;
                }
                else
                {
                    rowSet.insert(matrix[i][j]);
                }
                if (colSet.count(matrix[j][i]))
                {
                    return false;
                }
                else
                {
                    colSet.insert(matrix[j][i]);
                }
            }
            rowSet.clear();
            colSet.clear();
        }
        return true;
    }
};
  • T: O(N2)O(N^2)
  • S: O(N)O(N)