Count Servers That Communicate solution explained

The clean solution to Count Servers That Communicate makes two passes over the grid: first count how many servers sit in each row and each column, then count the servers whose row or column holds at least one other server. That runs in O(m·n) time with O(m + n) extra memory and needs no graph search at all.

By Published 9 min read

The problem in plain words

Picture a data center floor drawn as a grid with m rows and n columns. A cell holding 1 has a server in it and a cell holding 0 is empty. Two servers can exchange messages whenever they are in the same row or the same column, no matter how far apart they are and no matter what lies between them. Your job is to return how many servers can reach at least one other server. A server that is the only one in its row and the only one in its column is isolated, and it does not count.

Notice what the problem does not ask. It does not ask for groups, chains or the size of the largest network. A server only needs one partner directly in line with it. That detail is what keeps the answer simple, and candidates who miss it often start writing union-find or a flood fill that the question never needed.

Example grids written for this page
Grid (rows top to bottom)AnswerWhy
[1,0,0,1] / [0,0,1,0] / [1,0,0,0]3Row 0 has two servers, and the server at (2,0) shares column 0 with (0,0). The server at (1,2) is alone in row 1 and column 2.
[1,0] / [0,1]0Each server is alone on both of its lines, so nobody can talk.
[1,1,1]3One row holding three servers: every one has a partner.
[0,0] / [0,0]0No servers at all.
[1] / [1] / [0]2A single column with two servers in it.
Example grids written for this page. Scroll sideways on a small screen.

Questions worth asking before you code: can the grid be empty or have zero columns? Are the values strictly 0 and 1? How large can each side get? The answers decide whether a slow scan is acceptable.

Why this problem shows up in interviews

It looks like a graph question and tempts people into BFS. The signal the interviewer wants is whether you read the connection rule closely and notice that a direct line partner is enough. Candidates who explain that a server's status depends only on two numbers, its row total and its column total, tend to finish in fifteen minutes with time left for follow-ups. It also checks basic grid handling: zipping columns, avoiding index mix-ups between rows and columns, and handling a non-square shape.

Slow approach: scan each server's row and column

The direct translation of the rule is to visit each server and look along its row and down its column for another 1. As soon as you find one, count the server and move on. Each check costs up to m + n cells, and there can be up to m·n servers, so the worst case is O(m·n·(m + n)) time with O(1) extra memory. For a 250 by 250 grid that is roughly thirty million cell reads, which may pass in a compiled language and struggle in Python.

def talking_servers_slow(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    total = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != 1:
                continue
            partner = any(grid[r][k] == 1 for k in range(cols) if k != c) or \
                any(grid[k][c] == 1 for k in range(rows) if k != r)
            if partner:
                total += 1
    return total
Slow version: look along both lines for every server.

This version is still worth writing in a real round if you are stuck, because it is obviously correct and it doubles as the checker for your faster code.

Main approach: count each row and each column once

The slow version recomputes the same row and column many times. A row with ten servers gets scanned ten times. Instead, make one pass that fills two arrays: row_total[r] is the number of servers in row r, and col_total[c] is the number in column c. Then make a second pass. A server at (r, c) has a partner exactly when row_total[r] is at least 2 or col_total[c] is at least 2, because the totals include the server itself.

def talking_servers(grid):
    if not grid or not grid[0]:
        return 0
    row_total = [sum(row) for row in grid]
    col_total = [sum(col) for col in zip(*grid)]
    count = 0
    for r, row in enumerate(grid):
        for c, cell in enumerate(row):
            if cell == 1 and (row_total[r] > 1 or col_total[c] > 1):
                count += 1
    return count
Python: two passes, O(m·n) time and O(m + n) extra space.
function talkingServers(grid) {
  const rows = grid.length;
  const cols = rows ? grid[0].length : 0;
  if (rows === 0 || cols === 0) return 0;
  const rowTotal = new Int32Array(rows);
  const colTotal = new Int32Array(cols);
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === 1) {
        rowTotal[r]++;
        colTotal[c]++;
      }
    }
  }
  let count = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === 1 && (rowTotal[r] > 1 || colTotal[c] > 1)) count++;
    }
  }
  return count;
}
JavaScript: the same two passes with typed arrays for the totals.

A shorter way to say the same thing

You can also count the isolated servers and subtract. A server is isolated when its row total and its column total are both exactly 1. So the answer is the total number of servers minus the number of cells where grid[r][c] is 1, row_total[r] is 1 and col_total[c] is 1. It is the same work, but some interviewers like hearing the complement framing because it shows you see the structure from both sides.

A small refinement: while counting, remember the column of the server in any row whose total is 1. The second pass then checks only those lone-in-row servers against the column totals.

Walking through the first example

  1. Count rowsFor [1,0,0,1] / [0,0,1,0] / [1,0,0,0] the row totals are [2, 1, 1].
  2. Count columnsZipping the columns gives totals [2, 0, 1, 1].
  3. Check (0,0) and (0,3)Row 0 has a total of 2, so both servers in that row count. Running total: 2.
  4. Check (1,2)Row 1 total is 1 and column 2 total is 1. Isolated, so it is skipped.
  5. Check (2,0)Row 2 total is 1, but column 0 total is 2. It counts. Final answer: 3.

Complexity

Cost of each approach on an m by n grid
ApproachTimeExtra spaceNotes
Scan each server's linesO(m·n·(m + n))O(1)Easy to prove correct; useful as a checker
Row and column totalsO(m·n)O(m + n)The expected answer
Union-find over serversAbout O(m·n·α)O(m·n)Overkill here; fits a follow-up about network sizes
Cost of each approach on an m by n grid. Scroll sideways on a small screen.

You must read every cell at least once, so O(m·n) time is optimal. The two total arrays are the only extra memory, and they are tiny next to the grid itself.

Edge cases to test

  • A grid with no servers. The answer is 0 and nothing should crash on the zip of an all-zero grid.
  • A grid with exactly one server. It has no partner, so the answer is 0.
  • A single row or a single column. Every server counts as soon as there are two or more.
  • A diagonal pattern such as an identity matrix. Every server is isolated, so the answer is 0 even though the grid is full of servers.
  • A full grid of ones with at least two rows or two columns. Every server counts.
  • A non-square grid, such as 2 by 5. This catches code that uses the row count where it meant the column count.

Common mistakes

  • Treating it as connected components. A flood fill that only moves to adjacent cells gets the wrong answer, because servers do not need to be neighbors, only in line.
  • Checking row_total[r] > 0 instead of > 1. The total includes the server you are looking at, so a total of 1 means it is alone.
  • Counting pairs instead of servers. Three servers in a row is 3, not 3 pairs or 2 links.
  • Double counting a server that has partners in both its row and its column. Use one or check per cell, not two separate increments.
  • Swapping indexes when building column totals by hand, which only breaks on non-square grids and so slips past a square example.

Follow-ups an interviewer might add

  • Return the size of the largest group where communication can relay through intermediate servers. Now you do need union-find or BFS, joining each server with its row and column.
  • The grid is huge and sparse, given as a list of coordinates. Count with two dictionaries keyed by row and column instead of arrays.
  • Servers are added one at a time and you must report the count after each addition. Keep the totals and adjust the answer only for the new server and the line partners that just stopped being isolated.

How to explain it out loud

Fictional example

A short explanation for a phone screen
Candidate
A server only needs one partner in its row or its column, so I do not need a graph search. Whether it counts depends on two numbers: how many servers share its row and how many share its column.
Candidate
I will compute both totals in one pass, then make a second pass and count servers where either total is above one, since the total includes the server itself.
Candidate
That is linear in the number of cells, with extra space for one number per row and per column. I tested the identity matrix in my head: every total is 1, so the answer is 0, which matches.

If grids are on your list, Number of Enclaves is the natural next step: there the rule really is about adjacent cells, so a border flood fill replaces counting. For a graph problem that rewards a single linear pass, try Reorder Routes to Make All Paths Lead to the City Zero. The algorithm interview questions page covers the wider set of patterns.

Practicing with Natively

When you rehearse grid problems, Natively can read a screenshot of the prompt, suggest an approach and a complexity, and you can hold that up against the plan you wrote first. It also keeps a transcript of a spoken mock round on your own machine, so you can check afterward whether you said why a total of one means isolated. More on using AI in coding interview practice.

Questions people ask

What is the optimal solution to Count Servers That Communicate?

Count the servers in every row and every column in one pass, then count each server whose row total or column total is greater than one. That is O(m·n) time and O(m + n) extra space.

Do I need BFS or union-find for this problem?

No. A server only needs one other server in its row or column, so its status depends on two totals. Graph search only becomes necessary if the question asks for group sizes with relayed messages.

Why compare the row total with one and not zero?

The total includes the server you are checking. A total of exactly one means that server is alone on the line, so it needs a total of two or more to have a partner.

How do I handle a very large sparse grid?

Store server coordinates and count with two dictionaries keyed by row and by column. The logic stays the same and memory grows with the number of servers instead of the grid size.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP