KatInterview

891. Score After Flipping Matrix

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 for the highest possible score from a binary matrix, where the score is the sum of the numbers represented by each row. We can perform moves, which consist of toggling all values in a chosen row or column. The core challenge is to determine the optimal sequence of flips to maximize this total score.

Solution

Score After Flipping Matrix in Python

class Solution:
    def matrixScore(self, grid: list[list[int]]) -> int:
        m, n = len(grid), len(grid[0])

        # The score from the first column is fixed. After row flips,
        # it will be all 1s, contributing m * 2^(n-1) to the total score.
        score = m * (1 << (n - 1))

        # Iterate through the remaining columns
        for j in range(1, n):
            # Count the number of elements in column j that are the same
            # as the first element of their row. This equals the number
            # of 1s in this column after the initial row flips.
            same_count = 0
            for i in range(m):
                if grid[i][j] == grid[i][0]:
                    same_count += 1
            
            # We want to maximize the number of 1s in this column.
            # We can either have 'same_count' 1s or 'm - same_count' 1s (by flipping the column).
            # We choose the maximum of these two.
            ones_count = max(same_count, m - same_count)
            
            # Add the contribution of this column to the total score.
            score += ones_count * (1 << (n - 1 - j))
            
        return score

Score After Flipping Matrix in Java

class Solution {
    public int matrixScore(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        // Score is initialized with the contribution from the first column.
        // After potential row flips, the first column becomes all 1s.
        // Contribution from the first column is m * 2^(n-1).
        int score = m * (1 << (n - 1));

        // Iterate through the other columns.
        for (int j = 1; j < n; j++) {
            int sameCount = 0;
            // Count how many elements in column j are the same as the first element in their respective rows.
            // This is equivalent to counting the number of 1s in this column after row flips.
            for (int i = 0; i < m; i++) {
                if (grid[i][j] == grid[i][0]) {
                    sameCount++;
                }
            }

            // The number of 1s in this column can be either sameCount or m - sameCount (if we flip the column).
            // We take the maximum to maximize the score.
            int onesCount = Math.max(sameCount, m - sameCount);
            
            // Add the contribution of this column to the score.
            score += onesCount * (1 << (n - 1 - j));
        }

        return score;
    }
}

Score After Flipping Matrix in C++

class Solution {
public:
    int matrixScore(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        
        // The score is initialized with the contribution from the first column.
        // After row toggles, the first column will be all 1s.
        // Each row contributes 2^(n-1) from its MSB.
        // Use 1 << (n - 1) for pow(2, n - 1) for integer operations.
        int score = m * (1 << (n - 1));

        // Iterate over the remaining columns.
        for (int j = 1; j < n; ++j) {
            int same_count = 0;
            // Count how many cells in the current column have the same value as the first cell of their row.
            // This count represents the number of 1s in this column after the initial row toggles.
            for (int i = 0; i < m; ++i) {
                if (grid[i][j] == grid[i][0]) {
                    same_count++;
                }
            }
            
            // We want to maximize the number of 1s in this column.
            // If we toggle the column, the number of 1s becomes m - same_count.
            // So, we choose the larger of the two.
            int ones_count = std::max(same_count, m - same_count);
            
            // Add the contribution of this column to the total score.
            score += ones_count * (1 << (n - 1 - j));
        }
        
        return score;
    }
};

Score After Flipping Matrix in TypeScript

function matrixScore(grid: number[][]): number {
    const m = grid.length;
    const n = grid[0].length;

    // The score is initialized with the contribution from the most significant bit (first column).
    // After row flips, this column will be all 1s.
    // Each of the m rows contributes 2^(n-1).
    let score = m * (1 << (n - 1));

    // Iterate over the remaining columns.
    for (let j = 1; j < n; j++) {
        let sameCount = 0;
        // Count elements in the current column that match the first element of their row.
        // This count is the number of 1s in this column after the initial row flips.
        for (let i = 0; i < m; i++) {
            if (grid[i][j] === grid[i][0]) {
                sameCount++;
            }
        }
        
        // To maximize the score, we want the maximum number of 1s in this column.
        // This will be either 'sameCount' or 'm - sameCount' (if we flip the column).
        const onesCount = Math.max(sameCount, m - sameCount);
        
        // Add the contribution of this column to the total score.
        score += onesCount * (1 << (n - 1 - j));
    }

    return score;
};

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.