Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created January 23, 2025 21:55
Show Gist options
  • Save Ifihan/90ee43b83e55f02170c44c271b8a4a83 to your computer and use it in GitHub Desktop.
Save Ifihan/90ee43b83e55f02170c44c271b8a4a83 to your computer and use it in GitHub Desktop.
Count Servers that Communicate

Question

Approach

To solve the problem, I used an approach based on counting the number of servers in each row and column. First, I traversed the grid to calculate two arrays: row_count and col_count. row_count[i] stores the number of servers in row i, and col_count[j] stores the number of servers in column j.

Next, I performed a second traversal of the grid. For each server (grid[i][j] == 1), I checked if there were other servers in its row or column by evaluating whether row_count[i] > 1 or col_count[j] > 1. If either condition was true, the server was added to the count of communicating servers - res.

Implementation

class Solution:
    def countServers(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        row_count = [0] * m
        col_count = [0] * n

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    row_count[i] += 1
                    col_count[j] += 1

        res = 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):
                    res += 1
        
        return res

Complexities

  • Time: O(m * n)
  • Space: O(m * n
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment