Talentd
FleetCode
Make and follow sheets.Sign in

Count Servers that Communicate solution and explanation

MediumArrayBreadth-First SearchCountingDepth-First Search5 min read73.5% acceptanceUpdated 9 Apr 2026
Count Servers that Communicate - Leetcode 1267 - PythonNeetCodeIO · 11:59 · 10K viewsWatch on YouTube
9 more videos on this problem
  1. Count Servers that Communicate - Leetcode 1267 - PythonNeetCodeIO · 11:59 · 10K views
  2. Count Servers that Communicate | 3 Detailed Approaches | Dry Runs | Leetcode 1267 | codestorywithMIKcodestorywithMIK · 44:20 · 7K views
  3. Count Servers that Communicate | Leetcode 1267Techdose · 11:51 · 4K views
  4. Count Servers that Communicate (LeetCode 1267) | Full solution with visuals | Study AlgorithmsNikhil Lohia · 15:44 · 2K views
  5. 1267. Count Servers that Communicate | leetcode daily challenge | shashcode | java | dsa | shashwatShashCode · 9:28 · 1K views
  6. Leetcode | 1267. Count Servers that Communicate | Medium | JavaDeveloper Docs · 7:11 · 282 views
  7. 1267. Count Servers that Communicate | Leetcode Daily ChallengeEthos Typos · 8:56 · 185 views
  8. Count Servers That Communicate | LeetCode 1267 | Detailed Explanation with Examples in JavaRAHUL VIJAYAN · 9:43 · 96 views
  9. Count Servers that Communicate | LeetcodeAryan Codes · 7:45 · 58 views
  10. LeetCode Count Servers that Communicate Solution | 1267 | Step-by-Step Explanation | Code CrackCode Crack · 5:36 · 50 views

The problem

You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.

Return the number of servers that communicate with any other server.

Example 1:

Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.

Example 2:

Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.

Example 3:

Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 250
  • 1 <= n <= 250
  • grid[i][j] == 0 or 1

Approach overview

Problem Overview: You receive a binary m x n grid where 1 represents a server and 0 represents an empty cell. A server can communicate if there is at least one other server in the same row or column. The task is to count how many servers can communicate with another server.

Approach 1: Matrix Traversal (Brute Force) (Time: O(mn(m+n)), Space: O(1))

Iterate through every cell in the grid. When you encounter a server (grid[i][j] == 1), scan the entire row i and column j to check if another server exists. If at least one additional server appears in either direction, include the current server in the count. This method relies purely on repeated matrix traversal and avoids extra memory. The drawback is performance: each server triggers two additional scans, which makes the complexity grow to O(mn(m+n)). It works for small grids but becomes inefficient when the matrix size increases. The approach mainly reinforces basic matrix traversal techniques.

Approach 2: Row and Column Count (Time: O(mn), Space: O(m+n))

The key observation: a server communicates if its row or column contains more than one server. Instead of repeatedly scanning rows and columns, maintain two arrays: rowCount[m] and colCount[n]. First pass: iterate through the grid and increment counters whenever a server appears. Second pass: revisit each server and check if rowCount[i] > 1 or colCount[j] > 1. If true, that server can communicate. This reduces redundant work because row and column totals are computed once. The algorithm runs in linear time relative to the grid size. It is a common optimization pattern when solving array and matrix counting problems.

Recommended for interviews: The row and column counting approach is the expected solution. Interviewers want to see the transition from repeated scanning to precomputed counts. Starting with brute force demonstrates problem understanding, while the optimized two-pass counting solution shows awareness of time complexity and efficient data aggregation.

Approach 1: Row and Column Count

The problem can be solved by counting the servers in each row and column. If a server's row or column has more than one server, it can communicate with another server. Therefore, the solution consists of counting the number of servers in each row and column and then checking whether each server can communicate.

def countServers(grid):
    m, n = len(grid), len(grid[0])
    row_count = [0] * m
    col_count = [0] * n

    # First pass to calculate the number of servers in each 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 to count the servers that can communicate
    count = 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):
                count += 1

    return count
class Solution {
    public int countServers(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] row_count = new int[m];
        int[] col_count = new int[n];

        // Calculate the number of 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) {
                    row_count[i]++;
                    col_count[j]++;
                }
            }
        }

        int count = 0;
        // Count the servers that can communicate
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
}
#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> row_count(m, 0);
        vector<int> col_count(n, 0);

        // 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) {
                    row_count[i]++;
                    col_count[j]++;
                }
            }
        }

        int count = 0;
        // Count servers that can communicate
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
};
var countServers = function(grid) {
    const m = grid.length;
    const n = grid[0].length;
    const row_count = new Array(m).fill(0);
    const col_count = new Array(n).fill(0);

    // First pass to calculate the number of 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) { 
                row_count[i]++;
                col_count[j]++;
            }
        }
    }

    let count = 0;
    // Second pass to count the servers that can communicate
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                count++;
            }
        }
    }

    return count;
};
#include <stdio.h>
#include <stdlib.h>

int countServers(int** grid, int gridSize, int* gridColSize) {
    int* row_count = (int*)calloc(gridSize, sizeof(int));
    int* col_count = (int*)calloc(*gridColSize, sizeof(int));

    // First pass to calculate the number of servers in each row and column
    for (int i = 0; i < gridSize; i++) {
        for (int j = 0; j < *gridColSize; j++) {
            if (grid[i][j] == 1) {
                row_count[i]++;
                col_count[j]++;
            }
        }
    }

    int count = 0;
    // Second pass to count the servers that can communicate
    for (int i = 0; i < gridSize; i++) {
        for (int j = 0; j < *gridColSize; j++) {
            if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                count++;
            }
        }
    }

    free(row_count);
    free(col_count);

    return count;
}
public class Solution {
    public int CountServers(int[][] grid) {
        int m = grid.Length;
        int n = grid[0].Length;
        int[] row_count = new int[m];
        int[] col_count = new int[n];

        // Calculate the number of 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) {
                    row_count[i]++;
                    col_count[j]++;
                }
            }
        }

        int count = 0;
        // Count the servers that can communicate
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
}

This solution uses a two-pass approach. The first pass populates the row_count and col_count arrays, which store the count of servers in each row and column respectively. The second pass checks for each server if it can communicate with any other server and increments the count accordingly.

Complexity

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for storing row and column counts.

Try this approach in the editor

Approach 2: Matrix Traversal

The problem can alternatively be approached by directly traversing the matrix once, using auxiliary data structures to maintain counts of rows and columns. This helps in determining if a server at any particular cell can communicate by inspecting these counts directly.

def countServers(grid):
    from collections import defaultdict
    row_count, col_count = defaultdict(int), defaultdict(int)

    # Count the servers in each row and column
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == 1:
                row_count[i] += 1
                col_count[j] += 1

    # Check which servers can communicate
    count = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] == 1 and (row_count[i] > 1 or col_count[j] > 1):
                count += 1

    return count
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int countServers(int[][] grid) {
        Map<Integer, Integer> row_count = new HashMap<>();
        Map<Integer, Integer> col_count = new HashMap<>();

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    row_count.put(i, row_count.getOrDefault(i, 0) + 1);
                    col_count.put(j, col_count.getOrDefault(j, 0) + 1);
                }
            }
        }

        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1 && (row_count.get(i) > 1 || col_count.get(j) > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
}
#include <unordered_map>
#include <vector>
using namespace std;

class Solution {
public:
    int countServers(vector<vector<int>>& grid) {
        unordered_map<int, int> row_count, col_count;

        // Traverse the grid to track server counts
        for (int i = 0; i < grid.size(); ++i) {
            for (int j = 0; j < grid[0].size(); ++j) {
                if (grid[i][j] == 1) {
                    row_count[i]++;
                    col_count[j]++;
                }
            }
        }

        int count = 0;
        // Determine count of communicable servers
        for (int i = 0; i < grid.size(); ++i) {
            for (int j = 0; j < grid[0].size(); ++j) {
                if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
};
var countServers = function(grid) {
    let row_count = new Map();
    let col_count = new Map();

    // Traverse grid to calculate counts
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1) {
                row_count.set(i, (row_count.get(i) || 0) + 1);
                col_count.set(j, (col_count.get(j) || 0) + 1);
            }
        }
    }

    let count = 0;
    // Determine number of communicable servers
    for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
            if (grid[i][j] === 1 && (row_count.get(i) > 1 || col_count.get(j) > 1)) {
                count++;
            }
        }
    }

    return count;
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int countServers(int** grid, int gridSize, int* gridColSize) {
    int row_count[gridSize];
    int col_count[*gridColSize];
    memset(row_count, 0, sizeof(row_count));
    memset(col_count, 0, sizeof(col_count));

    // Traverse grid to fill counts
    for (int i = 0; i < gridSize; i++) {
        for (int j = 0; j < *gridColSize; j++) {
            if (grid[i][j] == 1) {
                row_count[i]++;
                col_count[j]++;
            }
        }
    }

    int count = 0;
    // Count servers that can communicate
    for (int i = 0; i < gridSize; i++) {
        for (int j = 0; j < *gridColSize; j++) {
            if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                count++;
            }
        }
    }
    return count;
}
public class Solution {
    public int CountServers(int[][] grid) {
        Dictionary<int, int> row_count = new Dictionary<int, int>();
        Dictionary<int, int> col_count = new Dictionary<int, int>();

        // Count servers in rows and columns
        for (int i = 0; i < grid.Length; i++) {
            for (int j = 0; j < grid[0].Length; j++) {
                if (grid[i][j] == 1) {
                    if (!row_count.ContainsKey(i)) row_count[i] = 0;
                    if (!col_count.ContainsKey(j)) col_count[j] = 0;
                    row_count[i]++;
                    col_count[j]++;
                }
            }
        }

        int count = 0;
        // Calculate communicable servers
        for (int i = 0; i < grid.Length; i++) {
            for (int j = 0; j < grid[0].Length; j++) {
                if (grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1)) {
                    count++;
                }
            }
        }

        return count;
    }
}

This approach uses Python's defaultdict to dynamically store and access the count of servers in rows and columns, allowing efficient traversal and checking within the grid.

Complexity

Time Complexity: O(m * n) for traversal.
Space Complexity: O(m + n) for auxiliary storage of counts.

Try this approach in the editor

Approach 3: Counting

We can count the number of servers in each row and each column, then traverse each server. If the number of servers in the current server's row or column exceeds 1, it means the current server meets the condition, and we increment the result by 1.

After the traversal, we return the result.

The time complexity is O(m times n), and the space complexity is O(m + n). Where m and n are the number of rows and columns in the matrix, respectively.

function countServers(grid: number[][]): number {
    const m = grid.length;
    const n = grid[0].length;
    const row = new Array(m).fill(0);
    const col = new Array(n).fill(0);
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            row[i] += grid[i][j];
            col[j] += grid[i][j];
        }
    }
    let ans = 0;
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] === 1 && (row[i] > 1 || col[j] > 1)) {
                ans++;
            }
        }
    }
    return ans;
}
func countServers(grid [][]int) (ans int) {
	m, n := len(grid), len(grid[0])
	row, col := make([]int, m), make([]int, n)
	for i := range grid {
		for j, x := range grid[i] {
			row[i] += x
			col[j] += x
		}
	}
	for i := range grid {
		for j, x := range grid[i] {
			if x == 1 && (row[i] > 1 || col[j] > 1) {
				ans++
			}
		}
	}
	return
}
impl Solution {
    pub fn count_servers(grid: Vec<Vec<i32>>) -> i32 {
        let m = grid.len();
        let n = grid[0].len();
        let mut row = vec![0; m];
        let mut col = vec![0; n];
        for i in 0..m {
            for j in 0..n {
                row[i] += grid[i][j];
                col[j] += grid[i][j];
            }
        }
        let mut ans = 0;
        for i in 0..m {
            for j in 0..n {
                if grid[i][j] == 1 && (row[i] > 1 || col[j] > 1) {
                    ans += 1;
                }
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Row and Column Count

Time Complexity: O(m * n) where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for storing row and column counts.

Matrix Traversal

Time Complexity: O(m * n) for traversal.
Space Complexity: O(m + n) for auxiliary storage of counts.

Counting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Matrix Traversal (Brute Force)O(mn(m+n))O(1)Useful for understanding the communication rule or when grid sizes are very small
Row and Column CountO(mn)O(m+n)Best general solution; avoids repeated scans by precomputing row and column server counts

Frequently asked questions

Is Count Servers that Communicate easy or hard?

The problem is rated Medium because the naive solution is straightforward but inefficient. Recognizing that row and column counts can be precomputed to eliminate repeated scans is the key insight that leads to the optimal approach.

Count Servers that Communicate Python/Java solution

Most implementations follow the same two-pass structure. First compute row and column counts, then iterate again to count servers where rowCount[i] > 1 or colCount[j] > 1. The logic translates directly across Python, Java, C++, and JavaScript.

How to solve Count Servers that Communicate in O(n)?

Treat the grid as having mn cells and process each cell only twice. Maintain row and column frequency arrays while traversing the matrix. A second pass checks whether each server shares its row or column with another server, giving an overall O(mn) solution.

What is the best approach for Count Servers that Communicate?

The most efficient approach is the row and column count technique. First count how many servers exist in each row and column using two arrays, then scan the grid again and include servers where the row or column count is greater than one. This solution runs in O(mn) time with O(m+n) extra space.

Is Count Servers that Communicate asked at Google/Amazon/Meta?

Grid counting and communication-style problems appear frequently in interviews at companies like Amazon, Google, and Meta. Variants often involve matrix traversal, connectivity detection, or counting elements that share rows or columns.

What data structure is used in Count Servers that Communicate?

The optimized solution uses simple arrays (or lists) to store row and column server counts. The problem itself is based on matrix traversal and counting, though alternative explorations can involve DFS, BFS, or Union Find to model server connectivity.

What is the time complexity of Count Servers that Communicate?

The optimal solution runs in O(mn) time where m is the number of rows and n is the number of columns. The grid is scanned twice: once to compute row and column counts, and once to determine which servers can communicate.

Comments

Now write it yourselfClose this page and solve Count Servers that Communicate in the editor, without looking.
Practise Count Servers that Communicate