Python 1267.py
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
width = len(grid[0])
height = len(grid)
rows = defaultdict(int)
cols = defaultdict(int)
for y in range(height):
for x in range(width):
cols[x] += grid[y][x]
rows[y] += grid[y][x]
result = 0
for y in range(height):
for x in range(width):
if grid[y][x] == 1 and (cols[x] > 1 or rows[y] > 1):
result += 1
return result
Difficulty
and has an acceptance rate of about 74% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Counting
- Depth First Search
- Matrix
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of counting servers that can communicate with at least one other server in a rectangular grid. A server is represented by the value 1 in the grid, and communication is possible when another server shares the same row or column. The algorithm proceeds in two distinct phases: first it aggregates the number of servers per row and per column, then it evaluates each cell to decide whether the server at that position meets the communication criterion.
Phase 1 - Aggregating row and column totals
The algorithm begins by determining the dimensions of the grid. It stores the width as the length of the first row and the height as the number of rows. Two dictionaries, rows and cols, are created using defaultdict(int) to hold the counts of servers for each row index and column index respectively.
width = len(grid[0])
height = len(grid)
rows = defaultdict(int)
cols = defaultdict(int)
for y in range(height):
for x in range(width):
cols[x] += grid[y][x]
rows[y] += grid[y][x]
During this double loop each cell contributes its value (either 0 or 1) to the corresponding row and column counters. Because the grid contains only binary values, the counters directly represent the number of servers present in each row and column. This single pass efficiently gathers all necessary statistics without redundant scanning.
Phase 2 - Identifying communicable servers
With the row and column totals available, the algorithm performs a second traversal of the grid. For each cell that contains a server (grid[y][x] == 1), it checks whether the server’s row or column contains more than one server. If either condition holds, the server can communicate and the result counter is incremented.
result = 0
for y in range(height):
for x in range(width):
if grid[y][x] == 1 and (cols[x] > 1 or rows[y] > 1):
result += 1
return result
The logical expression cols[x] > 1 or rows[y] > 1 captures the requirement that at least one peer exists in the same row or column. Servers that are isolated-those that are the sole 1 in both their row and column-are deliberately excluded from the final count.
Edge-case handling
The code gracefully manages several boundary conditions:
- All zeros - When the grid contains no servers, both
rowsandcolsdictionaries remain filled with zeros. The second pass never satisfies the conditiongrid[y][x] == 1, resulting in a final count of zero. - Single server - If exactly one cell holds a
1, its row and column counters each equal one. The condition(cols[x] > 1 or rows[y] > 1)evaluates to false, so the solitary server is not counted, correctly reflecting the lack of a communication partner. - Multiple servers in a single row - When several
1s share a row but occupy distinct columns, the row counter exceeds one while each column counter may remain one. The logical OR ensures that each of those servers is counted because the row condition is satisfied. - Multiple servers in a single column - The symmetric situation where servers share a column but not a row is handled analogously via the column counter.
- Rectangular grids - The algorithm does not assume a square shape; it uses separate width and height variables, allowing any rectangular configuration to be processed correctly.
- Minimal dimensions - For a grid consisting of a single row or a single column, the counting logic still applies because the dictionaries track counts per index, and the communication condition reduces to checking whether more than one server exists in that sole row or column.
Performance optimizations
The implementation incorporates several deliberate choices that enhance execution speed:
- Use of
defaultdict(int)- This eliminates the need for explicit existence checks before incrementing counters, reducing overhead in the inner loops. - Two-pass strategy - By separating the counting of row/column totals from the evaluation of each cell, the algorithm avoids nested scans that would otherwise lead to repeated counting of the same rows or columns.
- Direct integer addition - Adding the cell value directly to the counters leverages the fact that the grid contains only
0and1, avoiding conditional branches inside the accumulation loop. - Early exclusion of non-servers - The condition
grid[y][x] == 1is evaluated before the more expensive logical OR, ensuring that empty cells are skipped without unnecessary dictionary lookups. - Compact data structures - Storing only the aggregated counts rather than full row or column lists minimizes memory usage and improves cache locality during the second traversal.
Overall, the code delivers a clear, efficient solution that correctly accounts for all relevant edge cases while maintaining a low computational footprint through thoughtful use of data structures and loop organization.
ELI5 - Simplified Explanation
Imagine a giant grid that looks like a sheet of graph paper. Some squares have a little robot living inside them, and squares with a number one are the spots where these robots are hiding. The goal is to figure out how many robots have a friend nearby. A friend is any other robot sitting in the same row or the same column.
First, the code takes a trip through every single square on the grid to count how many robots are hiding in each row and each column. It keeps two lists like tally boards. One tally board keeps track of the robot count for every row, and the other one does the same for every column.
After counting everyone up, the code takes a second trip through the grid. This time, it stops at every square to check two things. It looks to see if a robot is standing there, and then it looks at the tally boards to see if that robot has any buddies in the same row or the same column. If the count for that row or column is bigger than one, it means there is at least one other robot sharing a line with the one in that square. Every time it finds a robot that is not alone, it adds that robot to a final count.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 2642: Design Graph With Shortest Path Calculator
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality