KatInterview

533. Lonely Pixel II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of "black lonely pixels" in a grid. A black pixel at (r, c) is defined as lonely if it satisfies a set of conditions. Let's break them down:

Solution

Lonely Pixel II in Python

class Solution:
    def findBlackPixel(self, picture: List[List[str]], target: int) -> int:
        m = len(picture)
        if m == 0:
            return 0
        n = len(picture[0])
        if n == 0:
            return 0

        # Pre-computation
        row_counts = [0] * m
        col_counts = [0] * n
        row_sigs = [""] * m
        sig_counts = collections.Counter()

        # Pass 1: Populate row-related information and signature counts
        for i in range(m):
            row_sigs[i] = "".join(picture[i])
            blacks_in_row = 0
            for j in range(n):
                if picture[i][j] == 'B':
                    blacks_in_row += 1
            row_counts[i] = blacks_in_row
            sig_counts[row_sigs[i]] += 1

        # Pass 2: Populate column counts
        for j in range(n):
            for i in range(m):
                if picture[i][j] == 'B':
                    col_counts[j] += 1

        # Pass 3: Count lonely pixels
        lonely_pixels = 0
        for i in range(m):
            # Optimization: check if this row can even have lonely pixels
            if row_counts[i] == target:
                # Check if this row is part of a valid group of identical rows
                if sig_counts[row_sigs[i]] == target:
                    for j in range(n):
                        if picture[i][j] == 'B' and col_counts[j] == target:
                            lonely_pixels += 1
        
        return lonely_pixels

Lonely Pixel II in Java

class Solution {
    public int findBlackPixel(char[][] picture, int target) {
        int m = picture.length;
        if (m == 0) return 0;
        int n = picture[0].length;
        if (n == 0) return 0;

        // Pre-computation
        int[] rowCounts = new int[m];
        int[] colCounts = new int[n];
        String[] rowSigs = new String[m];
        Map<String, Integer> sigCounts = new HashMap<>();

        // Pass 1: Populate row-related information and signature counts
        for (int i = 0; i < m; i++) {
            rowSigs[i] = new String(picture[i]);
            for (int j = 0; j < n; j++) {
                if (picture[i][j] == 'B') {
                    rowCounts[i]++;
                }
            }
            sigCounts.put(rowSigs[i], sigCounts.getOrDefault(rowSigs[i], 0) + 1);
        }

        // Pass 2: Populate column counts
        for (int j = 0; j < n; j++) {
            for (int i = 0; i < m; i++) {
                if (picture[i][j] == 'B') {
                    colCounts[j]++;
                }
            }
        }

        // Pass 3: Count lonely pixels
        int lonelyPixels = 0;
        for (int i = 0; i < m; i++) {
            // Optimization: Check if the row could contain lonely pixels
            if (rowCounts[i] == target) {
                // Check if this row is part of a valid group of identical rows
                if (sigCounts.get(rowSigs[i]) == target) {
                    for (int j = 0; j < n; j++) {
                        if (picture[i][j] == 'B' && colCounts[j] == target) {
                            lonelyPixels++;
                        }
                    }
                }
            }
        }

        return lonelyPixels;
    }
}

Lonely Pixel II in C++

class Solution {
public:
    int findBlackPixel(vector<vector<char>>& picture, int target) {
        int m = picture.size();
        if (m == 0) return 0;
        int n = picture[0].size();
        if (n == 0) return 0;

        // Pre-computation
        vector<int> row_counts(m, 0);
        vector<int> col_counts(n, 0);
        vector<string> row_sigs(m, "");
        unordered_map<string, int> sig_counts;

        // Pass 1: Populate row-related information and column counts
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (picture[i][j] == 'B') {
                    row_counts[i]++;
                    col_counts[j]++;
                }
            }
            row_sigs[i] = string(picture[i].begin(), picture[i].end());
        }

        // Pass 2: Populate signature counts
        for (const string& sig : row_sigs) {
            sig_counts[sig]++;
        }

        // Pass 3: Count lonely pixels
        int lonely_pixels = 0;
        for (int i = 0; i < m; ++i) {
            // Optimization: check if this row can even have lonely pixels
            if (row_counts[i] == target) {
                // Check if this row is part of a valid group of identical rows
                if (sig_counts[row_sigs[i]] == target) {
                    for (int j = 0; j < n; ++j) {
                        if (picture[i][j] == 'B' && col_counts[j] == target) {
                            lonely_pixels++;
                        }
                    }
                }
            }
        }

        return lonely_pixels;
    }
};

Lonely Pixel II in TypeScript

function findBlackPixel(picture: string[][], target: number): number {
    const m = picture.length;
    if (m === 0) return 0;
    const n = picture[0].length;
    if (n === 0) return 0;

    // Pre-computation
    const rowCounts: number[] = new Array(m).fill(0);
    const colCounts: number[] = new Array(n).fill(0);
    const rowSigs: string[] = new Array(m).fill('');
    const sigCounts: Map<string, number> = new Map();

    // Pass 1: Populate row-related information and signature counts
    for (let i = 0; i < m; i++) {
        rowSigs[i] = picture[i].join('');
        for (let j = 0; j < n; j++) {
            if (picture[i][j] === 'B') {
                rowCounts[i]++;
            }
        }
        sigCounts.set(rowSigs[i], (sigCounts.get(rowSigs[i]) || 0) + 1);
    }

    // Pass 2: Populate column counts
    for (let j = 0; j < n; j++) {
        for (let i = 0; i < m; i++) {
            if (picture[i][j] === 'B') {
                colCounts[j]++;
            }
        }
    }

    // Pass 3: Count lonely pixels
    let lonelyPixels = 0;
    for (let i = 0; i < m; i++) {
        // Optimization: Check if the row could contain lonely pixels
        if (rowCounts[i] === target) {
            // Check if this row is part of a valid group of identical rows
            if (sigCounts.get(rowSigs[i]) === target) {
                for (let j = 0; j < n; j++) {
                    if (picture[i][j] === 'B' && colCounts[j] === target) {
                        lonelyPixels++;
                    }
                }
            }
        }
    }

    return lonelyPixels;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.