Problem 861

Abstract / Summary

Given a binary matrix, flip rows to maximize ones, then flip one column to get the highest possible score.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0861.py

class Solution:
    def matrixScore(self, grid: List[List[int]]) -> int:
        width  = len(grid[0])
        height = len(grid)

        for y in range(height):
            if grid[y][0] == 0: # flip row
                for x in range(width):
                    grid[y][x] ^= 1

        # convert to integers
        scores = []
        for y in range(height):
            scores.append(0)
            for x in range(width):
                scores[y] <<= 1
                scores[y]  |= grid[y][x]

        # flip columns
        mask = 1 << width
        for x in range(width):
            flip = scores.copy()
            mask >>= 1
            for y in range(height):
                flip[y] ^= mask

            if sum(scores) < sum(flip):
                scores = flip

        return sum(scores)
30 lines | 835 bytes | submitted October 24, 2023 | GitHub   13% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Greedy
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the maximum possible sum of binary numbers represented by the rows of a binary matrix after performing any number of row and column flips. A row flip inverts every bit in that row, while a column flip inverts every bit in that column. The algorithm first guarantees that the most significant bit of each row is 1 by conditionally flipping rows, then interprets each row as an integer, and finally decides for each column whether flipping it increases the total sum. The final result is the sum of the integer values of the rows after the optimal set of flips.

Row Normalization

The first phase ensures that the left-most column (the most significant bit for each row) contains only 1s. This is achieved by scanning each row; if the first element is 0, the entire row is inverted using the XOR operator.

for y in range(height):
    if grid[y][0] == 0:               # flip row
        for x in range(width):
            grid[y][x] ^= 1

By forcing the leading bit to 1, the algorithm maximizes the contribution of each row because the most significant position carries the highest weight in binary representation.

Binary Conversion

After the rows are normalized, each row is transformed into its integer equivalent. The conversion builds the integer bit by bit, shifting the current value left and OR-ing the next bit.

scores = []
for y in range(height):
    scores.append(0)
    for x in range(width):
        scores[y] <<= 1
        scores[y]  |= grid[y][x]

The resulting list scores holds the numeric value of every row in its current state, ready for column-wise evaluation.

Column Optimization

The algorithm then evaluates each column from left to right (excluding the already-fixed most significant column) to decide whether flipping it yields a higher total sum. A mask representing the current column’s bit weight is generated by right-shifting a power-of-two mask. For each column, a tentative flipped version of scores is created by XOR-ing the mask with every row value. The sum of the original scores is compared with the sum of the flipped version; the version with the larger sum is retained.

mask = 1 << width
for x in range(width):
    flip = scores.copy()
    mask >>= 1
    for y in range(height):
        flip[y] ^= mask

    if sum(scores) < sum(flip):
        scores = flip

Because the most significant column has already been forced to 1, the loop effectively starts evaluating from the second column onward. The use of a copy (scores.copy()) preserves the original values while testing the effect of a column flip.

Edge Cases Handled

The code gracefully handles matrices of any rectangular shape, including a single row or a single column. When width equals 1, the column-flipping loop still executes, but the mask becomes 0 after the first right-shift, making the XOR operation a no-op; the comparison therefore leaves scores unchanged, which is correct because the leading column is already optimal. For a single row, the row-normalization step ensures the leading bit is 1, and the column-flipping stage evaluates each column independently, correctly maximizing the row’s binary value.

If the input matrix is empty or contains rows of differing lengths, the code would raise an exception at the initial size calculations; however, within the intended problem constraints (non-empty, well-formed binary matrix) the implementation covers all valid configurations.

Performance Optimizations

The algorithm avoids recomputing the entire matrix after each column decision. By working directly with integer representations (scores) and applying a bitwise XOR with a pre-computed mask, the column flip simulation runs in linear time with respect to the number of rows. The use of scores.copy() creates a shallow copy of the integer list, which is inexpensive compared to rebuilding the matrix from scratch.

The initial row-normalization step uses an in-place XOR to flip bits, eliminating the need for auxiliary storage. The subsequent binary conversion builds each integer in a single pass per row, leveraging bitwise shift and OR operations that are computationally cheap.

Overall, the solution achieves an efficient traversal pattern: one pass for row normalization, one pass for binary conversion, and a pass per column for optimization, each operating directly on compact integer data rather than on the original two-dimensional list. This design minimizes memory overhead and leverages fast bitwise primitives to keep the runtime low.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a large grid filled with zero and one tiles, like a big checkerboard. The goal is to make the total number represented by this grid as big as possible. Think of each row as a secret code made of numbers.

The code starts by looking at the very first number in every row. If that number is a zero, it flips every single tile in that row. Zeros become ones and ones become zeros. This happens because having a one at the start makes the whole row worth much more.

Next, the computer turns each row of tiles into a single number. It pretends the row is a tiny number machine that combines all the ones and zeros together.

After that, the code checks each column one by one. It imagines flipping all the tiles in a column to see if the total value gets bigger. If flipping that column produces a larger total, the computer keeps the change. This repeats for every column to ensure the final result is the biggest it can possibly be.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6.5 | μ = 6.42 | σ = 1.47

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C# Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
zfang399 C++
33 links | 19 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   October 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality