/**
* Problem: LeetCode 1267 - Count Servers that Communicate
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int countServers(int[][] grid) {
int m = grid.length, n = grid[0].length;
int[] rowCount = new int[m];
int[] colCount = new int[n];
// First pass: count servers in each row and column
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
rowCount[i]++;
colCount[j]++;
}
}
}
// Second pass: count servers that can communicate
int result = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && (rowCount[i] > 1 || colCount[j] > 1)) {
result++;
}
}
}
return result;
}
}
"""
Problem: LeetCode 1267 - Count Servers that Communicate
Difficulty: Medium
Language: Python (Python 3)
Author: CodeByTushu
"""
from typing import List
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
row_count = [0] * m
col_count = [0] * n
# First pass: precompute server frequencies per row and column
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
row_count[i] += 1
col_count[j] += 1
# Second pass: count servers with at least one communication partner
result = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (row_count[i] > 1 or col_count[j] > 1):
result += 1
return result
/**
* Problem: LeetCode 1267 - Count Servers that Communicate
* Difficulty: Medium
* Language: C++ (C++20)
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
class Solution {
public:
int countServers(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> rowCount(m, 0);
vector<int> colCount(n, 0);
// First pass: tally server counts per row and column
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
rowCount[i]++;
colCount[j]++;
}
}
}
// Second pass: count communicating servers
int result = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1 && (rowCount[i] > 1 || colCount[j] > 1)) {
result++;
}
}
}
return result;
}
};
/**
* Problem: LeetCode 1267 - Count Servers that Communicate
* Difficulty: Medium
* Language: JavaScript (Node.js ES2022)
* Author: CodeByTushu
*/
/**
* @param {number[][]} grid
* @return {number}
*/
var countServers = function(grid) {
const m = grid.length;
const n = grid[0].length;
const rowCount = new Array(m).fill(0);
const colCount = new Array(n).fill(0);
// First pass: count servers in each row and column
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1) {
rowCount[i]++;
colCount[j]++;
}
}
}
// Second pass: count communicating servers
let result = 0;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 1 && (rowCount[i] > 1 || colCount[j] > 1)) {
result++;
}
}
}
return result;
};