#1267

Count Servers that Communicate

Medium
ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * (m + n))
O(m * n)
Space
O(1)
O(m + n)
💡

Intuition

Time O(m * n)Space O(m + n)

We can optimize the process by counting the number of servers in each row and column first. This allows us to determine if a server can communicate without scanning the entire grid multiple times.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two arrays to count servers in each row and each column.
  2. 2Step 2: Traverse the grid and populate these counts.
  3. 3Step 3: Traverse the grid again, and for each server, check if its row or column count is greater than 1.
  4. 4Step 4: If yes, increment the total count of communicative servers.
solution.py14 lines
1def countServers(grid):
2    row_count = [0] * len(grid)
3    col_count = [0] * len(grid[0])
4    for i in range(len(grid)):
5        for j in range(len(grid[0])):
6            if grid[i][j] == 1:
7                row_count[i] += 1
8                col_count[j] += 1
9    count = 0
10    for i in range(len(grid)):
11        for j in range(len(grid[0])):
12            if grid[i][j] == 1 and (row_count[i] > 1 or col_count[j] > 1):
13                count += 1
14    return count

Complexity note: This complexity is efficient because we only traverse the grid a couple of times, leading to linear time complexity relative to the number of cells.

  • 1Servers communicate if they share the same row or column.
  • 2Counting servers in rows and columns can simplify the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.