Python 1582.py
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
height = len(mat)
width = len(mat[0])
x = [ 0 ] * width
y = [ 0 ] * height
for j in range(len(mat)):
y[j] = sum(mat[j])
for i in range(len(mat[j])):
x[i] += mat[j][i]
result = 0
for j in range(len(mat)):
if y[j] == 1:
for i in range(len(mat[j])):
if mat[j][i] == 1 and x[i] == 1:
result += 1
return result
Difficulty
and has an acceptance rate of about 73% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
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 computes the number of “special” cells in a binary matrix. A cell is considered special when it contains a 1 and it is the only 1 in both its row and its column. The algorithm proceeds in two phases: first it aggregates the counts of 1s per row and per column, then it scans the matrix again to identify cells that satisfy the uniqueness condition.
Key Steps
The first phase builds two auxiliary arrays that store the sum of each column and each row.
height = len(mat)
width = len(mat[0])
x = [0] * width # column counters
y = [0] * height # row counters
for j in range(len(mat)):
y[j] = sum(mat[j]) # total 1s in row j
for i in range(len(mat[j])):
x[i] += mat[j][i] # accumulate 1s in column i
x[i] ends up holding the number of 1s in column i, while y[j] holds the number of 1s in row j. The use of sum for each row provides a concise way to compute row totals, and the inner loop updates column totals in a single pass over the matrix.
The second phase iterates over rows that contain exactly one 1. For each such row, it checks the column of that 1 to verify that the column also contains exactly one 1. When both conditions hold, the result counter is incremented.
result = 0
for j in range(len(mat)):
if y[j] == 1: # row j has a single 1
for i in range(len(mat[j])):
if mat[j][i] == 1 and x[i] == 1: # column i also has a single 1
result += 1
The final value of result is returned as the count of special cells.
return result
Edge Cases Handled
The algorithm gracefully handles matrices of any rectangular shape, including single-row or single-column inputs. When the matrix consists of a single row, the column counters x are still correctly populated, and the row check y[j] == 1 ensures that only rows with a solitary 1 are considered. Similarly, for a single column, the row counters y capture the presence of 1s, and the column check x[i] == 1 validates uniqueness in that column.
If the matrix contains no 1s at all, both x and y arrays remain zero, the condition y[j] == 1 never triggers, and the function returns 0.
When every cell is 1, each row and column count equals the respective dimension, so the condition y[j] == 1 fails for every row, again yielding a result of 0.
The code also tolerates rows of varying lengths only insofar as the input respects the rectangular assumption (len(mat[0]) defines the width). Within that constraint, the inner loops use the actual length of each row (len(mat[j])), ensuring correct indexing even if the matrix were constructed with consistent dimensions but different internal list objects.
Performance Optimizations
The implementation avoids redundant scans by computing both row and column totals in a single nested loop. This eliminates the need for a separate pass solely for column aggregation.
By checking y[j] == 1 before entering the inner column loop of the second phase, the algorithm skips entire rows that cannot contribute a special cell, reducing unnecessary element accesses.
The use of plain Python lists for the counters (x and y) provides fast indexed updates and lookups, leveraging the interpreter’s optimized list operations.
Overall, the two-pass structure-first to gather aggregates, second to validate candidates-delivers a concise solution that balances readability with efficient use of iteration.
ELI5 - Simplified Explanation
Imagine a big square grid filled with boxes. Some boxes have a shiny jewel inside, which we represent with the number one, and some are just empty with a zero. The goal is to find how many special jewels exist. A jewel is special if it is the only one in its row and also the only one in its column.
To find these, the computer first looks through the whole grid. It counts how many jewels are in every row and saves those counts in a list. Then it does the same thing for every column, counting the jewels in each one and saving those counts in another list.
After those lists of counts are ready, the computer looks at every box one more time. It checks if the row has exactly one jewel and if the column has exactly one jewel. If it finds a jewel in a box that has only one jewel in its row and only one jewel in its column, it knows that jewel is special. It keeps a tally of all these special jewels as it goes along.
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 | C# | C | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| pruthvikp | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| withaarzoo | C++ | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2482: Difference Between Ones and Zeros in Row and Column
Solved On The Same Day
- problem 1022: Sum of Root To Leaf Binary Numbers
- problem 2331: Evaluate Boolean Binary Tree
- problem 449: Serialize and Deserialize BST
- problem 894: All Possible Full Binary Trees
- problem 919: Complete Binary Tree Inserter
- problem 951: Flip Equivalent Binary Trees
- problem 2415: Reverse Odd Levels of Binary Tree
- problem 297: Serialize and Deserialize Binary Tree
- problem 834: Sum of Distances in Tree
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