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
rowandcolumn - second pass to see how many servers can communicate with another server (i.e. be present in a
roworcolumnwith count greater than1)
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)wheremdenotesgrid.size()andndenotesgrid[0].size()- Space:
O(m + n)
time taken link to time taken
- 10 minutes and 38 seconds