Problem Description
Given an m x n picture (2D grid) where each cell is either 'B' (black) or 'W' (white) and an integer target, return the number of black lonely pixels. A black pixel at (r, c) is considered lonely if:
- Row r and column c each contain exactly target black pixels.
- For every row that has a black pixel at column c, that row is exactly the same as row r.
Key Insights
- We must count black pixels per row and per column.
- Only rows with exactly target black pixels can possibly contribute.
- For a potential valid row, all black pixels in that row must lie in columns that also have exactly target black pixels.
- Identical rows that meet the criteria can be grouped together; however, they are only valid if the group size equals target.
- The final answer is the sum of valid black pixels in these qualifying rows.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(m * n) in the worst-case due to storing row strings and column counts.
Solution
We use a two-step approach:
- Process each row to:
- Count black pixels in the row.
- Build a string representation of the row.
- Maintain a frequency map for rows that have exactly target black pixels.
- At the same time, update a column counter to track black pixels per column.
- For each row pattern in our frequency map:
- Check that the frequency equals target (ensuring exactly target rows are identical).
- For every column position with a black pixel in the row pattern, verify that its column count is exactly target.
- If valid, every black pixel in these rows is counted toward the result (each valid row contributes target valid pixels).
This approach leverages simple counting with hash maps and arrays and ensures that we only count pixels that satisfy both the row and column conditions.