Problem 1582

Abstract / Summary

Count rows and columns with exactly one zero and return how many cells are in both such rows and columns.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
19 lines | 575 bytes | submitted December 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.00 | σ = 0.78

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
32 links | 18 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   December 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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