Lonely Pixel I — LeetCode 531 Python Solution

MediumLeetCode PremiumArrayHash TableMatrix
Problem
#531
Reading time
3 min

The problem

Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels. A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.

Example

Input
picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
Output
3
Explanation
All the three 'B's are black lonely pixels.

Python solution

Python
class Solution:
    def findLonelyPixel(self, picture: List[List[str]]) -> int:
        rows = [0] * len(picture)
        cols = [0] * len(picture[0])
        for i, row in enumerate(picture):
            for j, x in enumerate(row):
                if x == "B":
                    rows[i] += 1
                    cols[j] += 1
        ans = 0
        for i, row in enumerate(picture):
            for j, x in enumerate(row):
                if x == "B" and rows[i] == 1 and cols[j] == 1:
                    ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m + n), where m and n are the number of rows and columns in the matrix respectively auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 531. Lonely Pixel I is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 531. Lonely Pixel I?
LeetCode 531. Lonely Pixel I is rated Medium on LeetCode.
What is the time complexity of LeetCode 531. Lonely Pixel I?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 531. Lonely Pixel I?
The Python solution on this page uses O(m + n), where m and n are the number of rows and columns in the matrix respectively auxiliary space.
What topics does LeetCode 531. Lonely Pixel I cover?
LeetCode 531. Lonely Pixel I is tagged Array, Hash Table and Matrix on LeetCode.
Is LeetCode 531. Lonely Pixel I a premium problem?
Yes. LeetCode 531. Lonely Pixel I is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview