Count Servers that Communicate - Problem

Imagine you're managing a data center network where servers need to communicate with each other. You have a rectangular grid representing the server room layout, where 1 indicates a server is present and 0 means the position is empty.

Servers can communicate if they are in the same row or same column. A server that can communicate with at least one other server is considered "active in the network".

Goal: Count how many servers are actively participating in network communication.

Example: In a 2ร—3 grid [[1,0,1],[1,0,1]], all 4 servers can communicate (servers in same rows/columns), so the answer is 4.

Input & Output

example_1.py โ€” Basic Grid
$ Input: grid = [[1,0],[0,1]]
โ€บ Output: 0
๐Ÿ’ก Note: No server can communicate. Each server is alone in its row and column.
example_2.py โ€” Multiple Communications
$ Input: grid = [[1,0,1],[1,0,1]]
โ€บ Output: 4
๐Ÿ’ก Note: All 4 servers communicate. Row 0 has 2 servers, row 1 has 2 servers, columns 0&2 each have 2 servers.
example_3.py โ€” Single Server
$ Input: grid = [[1]]
โ€บ Output: 0
๐Ÿ’ก Note: Only one server exists, so it cannot communicate with anyone.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m โ‰ค 250
  • 1 โ‰ค n โ‰ค 250
  • grid[i][j] == 0 or 1

Visualization

Tap to expand
Server Communication NetworkS1--S2S3--S4โœ… All servers can communicate through row/column connectionsRed lines show communication paths
Understanding the Visualization
1
Scan Network
Count active servers on each network segment (row/column)
2
Identify Clusters
Servers on segments with 2+ servers can communicate
3
Count Active
Sum up all servers that are part of communication clusters
Key Takeaway
๐ŸŽฏ Key Insight: A server communicates if its row OR column has multiple servers - no need to check individual connections!
Asked in
Amazon 45 Google 38 Microsoft 28 Meta 22
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K 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