LeetCode 1267: Count Servers that Communicate Solution

Master LeetCode problem 1267 (Count Servers that Communicate), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

  • We can solve this problem by counting the number of servers in each row and each column.
  • For each server, if there is more than one server in its row or column, we increment the total count.
  • Finally, we return the total count of servers that can communicate with at least one other server.

Time Complexity:

The time complexity of this solution is O(m * n), where m is the number of rows and n is the number of columns in the grid.

Space Complexity:

The space complexity of this solution is O(m + n), where m is the number of rows and n is the number of columns in the grid.

:

Solution Code

class Solution {
    public int countServers(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] rows = new int[m];
        int[] cols = new int[n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    rows[i]++;
                    cols[j]++;
                }
            }
        }
        
        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) {
                    count++;
                }
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1267 (Count Servers that Communicate)?

This page provides optimized solutions for LeetCode problem 1267 (Count Servers that Communicate) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1267 (Count Servers that Communicate)?

The time complexity for LeetCode 1267 (Count Servers that Communicate) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1267 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1267 in Java, C++, or Python.

Back to LeetCode Solutions