← leetcode

Count Servers that Communicate

· Medium

LeetCode problem 1267

i've done this question before apparently.

this time however, i decided to just do two passes:

  • first pass to count the number of servers present in every row and column
  • second pass to see how many servers can communicate with another server (i.e. be present in a row or column with count greater than 1)

code link to code

class Solution {
public:
    int countServers(vector<vector<int>>& grid) {
        int m {static_cast<int>(grid.size())}, n {static_cast<int>(grid[0].size())};

        vector<int> row(m, 0);
        vector<int> col(n, 0);

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    ++row[i]; 
                    ++col[j];
                }
            }
        }

        int ans{};
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && (row[i] > 1 || col[j] > 1)) {
                    ++ans;
                }
            }
        }
        return ans;
    }
};

complexity link to complexity

  • Time: O(mn) where m denotes grid.size() and n denotes grid[0].size()
  • Space: O(m + n)

time taken link to time taken

  • 10 minutes and 38 seconds