|
| 1 | +# [Problem 1582: Special Positions in a Binary Matrix](https://leetcode.com/problems/special-positions-in-a-binary-matrix/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +We need to count positions (i, j) where mat[i][j] == 1 and every other element in row i and column j is 0. The brute force way would be: for every 1, scan its entire row and column to verify there are no other 1s — that would be O(m + n) work per 1 and in worst case O(mn(m+n)), which is unnecessary for constraints up to 100x100 but still suboptimal. |
| 5 | + |
| 6 | +A common pattern: precompute the count of 1s in each row and each column. If a cell is 1 and its row-count == 1 and its col-count == 1, it's special. That gives a single pass to compute counts and another pass to count special positions — overall O(mn) time. |
| 7 | + |
| 8 | +## Refining the problem, round 2 thoughts |
| 9 | +- Edge cases: all zeros -> answer 0. All ones -> usually 0 unless matrix is 1x1. |
| 10 | +- Precomputing row and column sums is straightforward and stable. |
| 11 | +- Space: need O(m + n) extra space for the counts, which is fine for m,n <= 100. |
| 12 | +- Alternative in-place trick: you could encode counts into existing matrix to save auxiliary space, but it's unnecessary here and less clear. |
| 13 | +- Complexity: two passes over the matrix -> O(mn) time, O(m + n) extra space. |
| 14 | + |
| 15 | +## Attempted solution(s) |
| 16 | +```python |
| 17 | +from typing import List |
| 18 | + |
| 19 | +class Solution: |
| 20 | + def numSpecial(self, mat: List[List[int]]) -> int: |
| 21 | + if not mat or not mat[0]: |
| 22 | + return 0 |
| 23 | + m, n = len(mat), len(mat[0]) |
| 24 | + # Compute row counts |
| 25 | + row_count = [sum(row) for row in mat] |
| 26 | + # Compute column counts |
| 27 | + col_count = [0] * n |
| 28 | + for j in range(n): |
| 29 | + s = 0 |
| 30 | + for i in range(m): |
| 31 | + s += mat[i][j] |
| 32 | + col_count[j] = s |
| 33 | + |
| 34 | + # Count special positions |
| 35 | + ans = 0 |
| 36 | + for i in range(m): |
| 37 | + for j in range(n): |
| 38 | + if mat[i][j] == 1 and row_count[i] == 1 and col_count[j] == 1: |
| 39 | + ans += 1 |
| 40 | + return ans |
| 41 | +``` |
| 42 | +- Notes: |
| 43 | + - Approach: precompute number of 1s in each row and column, then count cells where mat[i][j] == 1 and both corresponding counts are exactly 1. |
| 44 | + - Time complexity: O(m * n) — one pass to compute row counts (O(mn) inside sum across rows) and one pass for column counts (O(mn)), plus final check pass (O(mn)). |
| 45 | + - Space complexity: O(m + n) for row_count and col_count arrays. |
| 46 | + - Implementation detail: using Python's sum(row) for rows is concise; columns computed by iterating rows for each column is clear and efficient for given constraints. |
0 commit comments