Problem 2643

Abstract / Summary

Find the row that has the most 1s in a given set of rows made up of 0s and 1s.

Note

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

Python 2643.py

class Solution:
    def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
        total = [ sum(row) for row in mat ]
        return  [ total.index(max(total)), max(total) ]
4 lines | 188 bytes | submitted February 21, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • 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 defines a single method rowAndMaximumOnes that receives a two-dimensional list mat representing a binary matrix. Its purpose is to identify the row that contains the greatest number of 1 values and to return both the index of that row and the count of 1s found. The solution relies on Python’s built-in aggregation functions and list comprehensions to achieve the result in a compact form.

Key Steps and Corresponding Code

The algorithm can be broken down into two logical phases. The first phase computes the number of 1s in each row, while the second phase extracts the row index with the maximum count and the count itself.

Phase 1 - Row Summation

total = [ sum(row) for row in mat ]

In this line a list comprehension iterates over each row in the input matrix. The built-in sum function adds the integer elements of the row, which, because the matrix is binary, directly yields the count of 1s. The resulting list total holds the per-row counts in the same order as the original matrix.

Phase 2 - Determining the Maximum Row

return [ total.index(max(total)), max(total) ]

The expression max(total) finds the highest count of 1s across all rows. The call to total.index(...) then returns the first position where this maximum value occurs, which corresponds to the smallest row index in case of a tie. The method finally returns a two-element list containing the identified row index and the maximum count.

Edge Cases Handled

When the matrix contains rows that are entirely 0s, the sum operation yields 0 for those rows, and the algorithm correctly identifies the row with the highest count, even if that count is 0. If multiple rows share the same maximum number of 1s, the use of list.index ensures that the earliest (lowest index) row is selected, providing deterministic behavior. The code also gracefully processes rows of varying lengths because sum operates on each row independently; the length of a row does not affect the correctness of the count.

Performance Optimizations Observed

The solution leverages Python’s highly optimized C-level implementations of sum, max, and list.index. By using a list comprehension for the summation, the code avoids explicit Python loops, reducing interpreter overhead. The single pass to compute total and the subsequent built-in calls each traverse the data only once, minimizing the number of iterations required. Additionally, the reuse of max(total) in both the index lookup and the return value prevents redundant calculations, as the maximum is computed a single time and stored implicitly by the interpreter during the expression evaluation. This approach yields a concise and efficient solution for the problem at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid like a treasure map filled with boxes. Some boxes have a one inside, and some have a zero. This code looks at every row of boxes one by one and counts how many ones are sitting in each row. It keeps a secret list where it writes down those counts so it can remember which row was the winner. After checking all the rows, the code finds the highest number of ones ever seen. It then picks out the very first row that had that many ones and tells you both the row number and the total count of those ones.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.85 | σ = 1.18

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 Java Python C++ TS
WalkCCC Java Python C++
leetcode.ca Java Python C++ C# Go Rust TS
Progiez Java Python C++
github charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
varunu28 Java
23 links | 10 authors | 8 languages

Videos

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

Solved On The Same Day

1 easy 2 medium 1 hard
5 solutions   February 21, 2024

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