Knowledge Guide
HomeDSAMatrix

easy Problem 3 Row With Maximum Ones

Problem Statement

Given a binary matrix that has dimensions , consisting of ones and zeros, determine the row that contains the highest number of ones and return two values: the zero-based index of this row and the actual count of ones it possesses.

If there is a tie, i.e., multiple rows contain the same maximum number of ones, we must select the row with the lowest index.

Examples

Example 1:

Example 2:

Example 3:

Constraints:

Try it yourself

Try solving this question here:

✅ Solution Row With Maximum Ones

Problem Statement

Given a binary matrix that has dimensions , consisting of ones and zeros. Determine the row that contains the highest number of ones and return two values: the zero-based index of this row and the actual count of ones it possesses.

If there is a tie, i.e., multiple rows contain the same maximum number of ones, we must select the row with the lowest index.

Examples

Example 1:

  • Input: [[1, 0], [1, 1], [0, 1]]
  • Expected Output: [1, 2]
  • Justification: The second row [1, 1] contains the most ones, so the output is [1, 2].

Example 2:

  • Input: [[0, 1, 1], [0, 1, 1], [1, 1, 1]]
  • Expected Output: [2, 3]
  • Justification: The third row [1, 1, 1] has the most ones, leading to the output [2, 3].

Example 3:

  • Input: [[1, 0, 1], [0, 0, 1], [1, 1, 0]]
  • Expected Output: [0, 2]
  • Justification: Both the first and third rows contain two ones, but we choose the first due to its lower index, resulting in [0, 2].

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • mat[i][j] is either 0 or 1.

Solution

The fundamental task is to identify the row with the maximum number of ones and simultaneously track the number of ones in this row.

To solve this problem, we will systematically examine each row of a given binary matrix to identify the row with the highest number of 1s. The solution involves iterating over each row, counting the 1s present, and comparing this count with the highest number of 1s recorded so far. We maintain two variables: one for the highest count of 1s encountered, and another for the index of the row where this occurred. This method ensures we check every element in the matrix precisely once, leading to an efficient approach in determining the row that contains the maximum number of 1s.

Step-by-Step Algorithm

  1. Initialize Variables: Set up two variables: maxOnesCount, initially 0, for tracking the maximum number of 1s found in any row; and maxOnesIdx, initially 0, for storing the index of the row with this maximum count.

  2. Iterate Through Each Row: Loop through each row of the matrix. For every row, perform the following steps:

    a. Count 1s in the Current Row: Initialize a counter for the number of 1s in this row. Traverse through each element of the row, incrementing the counter for each 1 encountered.

    b. Update Maximum Count and Row Index: If the count of 1s in the current row exceeds maxOnesCount, update maxOnesCount with the new count and set maxOnesIdx to the current row's index.

  3. Handling No 1s Scenario: If no 1s are found in the entire matrix, maxOnesIdx and maxOnesCount remain 0.

  4. Return the Result: At the end of the iteration, return [maxOnesIdx, maxOnesCount].

Algorithm Walkthrough

Image
Image
  • Initialize maxOnesIdx to 0 and maxOnesCount to 0.
  • Loop through each row:
    • Row 0 [1, 0, 1]: Count of ones = 2. It is greater than maxOnesCount so update maxOnesIdx to 0 and maxOnesCount to 2.
    • Row 1 [0, 0, 1]: Count of ones = 1. It is not greater than maxOnesCount, no update occurs.
    • Row 2 [1, 1, 0]: Count of ones = 2. It is equal to maxOnesCount, so no update occurs to maintain the smallest index.
  • Return [maxOnesIdx, maxOnesCount] which yields [0, 2].

Here is the visual representation of the algorithm:

Code

Here is the code for this algorithm:

java
public class Solution {

  public int[] findMaxOnesRow(int[][] mat) {
    int maxOnesIdx = 0;
    int maxOnesCount = 0;
    // Traverse through rows
    for (int i = 0; i < mat.length; i++) {
      int onesCount = 0;
      // Count ones in the current row
      for (int j = 0; j < mat[i].length; j++) {
        onesCount += mat[i][j];
      }
      // Check and update tracking variables if needed
      if (onesCount > maxOnesCount) {
        maxOnesIdx = i;
        maxOnesCount = onesCount;
      }
    }
    return new int[] { maxOnesIdx, maxOnesCount };
  }

  // Main method for testing
  public static void main(String[] args) {
    Solution sol = new Solution();
    // Applying example inputs
    int[] result1 = sol.findMaxOnesRow(
      new int[][] { { 1, 0 }, { 1, 1 }, { 0, 1 } }
    );
    System.out.println(result1[0] + ", " + result1[1]); // Output: 1, 2

    int[] result2 = sol.findMaxOnesRow(
      new int[][] { { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 1 } }
    );
    System.out.println(result2[0] + ", " + result2[1]); // Output: 2, 3

    int[] result3 = sol.findMaxOnesRow(
      new int[][] { { 1, 0, 1 }, { 0, 0, 1 }, { 1, 1, 0 } }
    );
    System.out.println(result3[0] + ", " + result3[1]); // Output: 0, 2
  }
}

Complexity Analysis

Time Complexity

  • Outer loop (rows): The outer loop iterates through each row of the matrix. If there are M rows, this loop runs times.

  • Inner loop (columns): For each row, the inner loop counts the number of ones by iterating through all the columns. If each row has N columns, the inner loop runs times for each row.

  • Therefore, the total time complexity is , where M is the number of rows and N is the number of columns in the matrix.

Overall time complexity: .

Space Complexity

  • Constant space: The algorithm uses a few additional variables (maxOnesIdx, maxOnesCount, and onesCount), all of which require constant space, .

  • The result array new int[]{maxOnesIdx, maxOnesCount} also takes constant space, .

Overall space complexity: .

🤖 Don't fully get this? Learn it with Claude

Stuck on Problem 3 Row With Maximum Ones? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Problem 3 Row With Maximum Ones** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Problem 3 Row With Maximum Ones** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Problem 3 Row With Maximum Ones**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Problem 3 Row With Maximum Ones**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes