Count Servers that Communicate - 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 there 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.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[1,0],[0,1]]
Output: 0
💡 Note: No server can communicate with any other server. Server at (0,0) has no other server in row 0 or column 0. Server at (1,1) has no other server in row 1 or column 1.
Example 2 — Same Row Communication
$ Input: grid = [[1,0],[1,1]]
Output: 3
💡 Note: Server (1,0) and (1,1) can communicate (same row). Server (0,0) and (1,0) can communicate (same column). All 3 servers can communicate.
Example 3 — Mixed Communication
$ Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
💡 Note: Servers (0,0) and (0,1) communicate via same row. Servers (1,2) and (2,2) communicate via same column. Server (3,3) is isolated. Total: 4 servers communicate.

Constraints

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

Visualization

Tap to expand
Count Servers that Communicate INPUT Server Grid (2x2) 1 0 0 1 R0 R1 C0 C1 grid = [[1,0],[0,1]] 2 servers diagonal = Server (1) = Empty (0) ALGORITHM STEPS 1 Count Row Servers Row 0: 1, Row 1: 1 2 Count Col Servers Col 0: 1, Col 1: 1 3 Check Each Server If row[i]>1 OR col[j]>1 4 Count Communicating Server can talk to another Pass 1 Counts: rowCount = [1, 1] colCount = [1, 1] No row/col has count > 1 FINAL RESULT Isolated Servers X X Both servers ISOLATED No shared row or column Output: 0 0 servers communicate [OK] Result verified Key Insight: A server communicates only if there's another server in the SAME row OR SAME column. Two-Pass approach: First count servers per row/col, then check each server if row[i] > 1 OR col[j] > 1. Time: O(m*n) | Space: O(m+n) for row and column count arrays TutorialsPoint - Count Servers that Communicate | Two-Pass Count Approach
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
32.1K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen