Row with max 1s in Sorted Matrix (original) (raw)

Given a m * n binary matrix mat**[][]** consisting of only **1's**and 0' s. Each row of the array is *sorted in non-decreasing order. Find and return the index of the first row that contains the maximum number of 1' s. If no such row exists, return-1*.

**Examples:

**Input: mat[][] = [[ 0 0 1 1 ]
[0 1 1 1 ]
[0 0 1 1 ]
[0 0 0 0 ]]
**Output: 1
**Explanation: row = 1 has maximum number of 1's, that is 3.

**Input: mat[][] **= [ [ 0 1 1 1 ]
[ 0 0 1 1 ]
[ 1 1 1 1 ]
[ 0 0 0 0 ]]
**Output: 2
**Explanation: row = 2 has maximum number of 1's, that is 4.

Table of Content

[Naive Approach] Row-wise traversal - O(m * n) Time and O(1) Space:

A simple method is to do a row-wise traversal of the matrix, count the number of 1s in each row, and compare the count with the max. Finally, return the index of the row with a maximum of 1's.

C++ `

#include #include

using namespace std;

// Function to find the index of the row containing the maximum number of 1s. int rowWithMax1s(vector<vector>& mat) {

int rowIndex = -1;
int maxCount = 0;

int m = mat.size();
int n = mat[0].size();

// Iterate through each row of the matrix
for (int i = 0; i < m; i++) {
    
    int count = 0;
    
    // Iterate through each column in the current row
    for (int j = 0; j < n; j++) {
        
        // If a 1 is found, increment the count for this specific row
        if (mat[i][j] == 1) {
            count++;
        }
    }
    
    // If the current row has more 1s than our previously recorded maximum,
    // update the maximum count and store the current row index
    if (count > maxCount) {
        maxCount = count;
        rowIndex = i;
    }
}

return rowIndex;

}

int main() {

vector<vector<int>> mat = {
    {0, 1, 1, 1},
    {0, 0, 1, 1},
    {1, 1, 1, 1},
    {0, 0, 0, 0}
};

cout << rowWithMax1s(mat) << "\n";

return 0;

}

Java

class GFG {

// Function to find the index of the row containing the
// maximum number of 1s.
static int rowWithMax1s(int[][] mat)
{

    int rowIndex = -1;
    int maxCount = 0;

    int m = mat.length;
    int n = mat[0].length;

    // Iterate through each row of the matrix
    for (int i = 0; i < m; i++) {

        int count = 0;

        // Iterate through each column in the current
        // row
        for (int j = 0; j < n; j++) {

            // If a 1 is found, increment the count for
            // this specific row
            if (mat[i][j] == 1) {
                count++;
            }
        }

        // If the current row has more 1s than our
        // previously recorded maximum, update the
        // maximum count and store the current row index
        if (count > maxCount) {
            maxCount = count;
            rowIndex = i;
        }
    }

    return rowIndex;
}

public static void main(String[] args)
{

    int[][] mat = { { 0, 1, 1, 1 },
                    { 0, 0, 1, 1 },
                    { 1, 1, 1, 1 },
                    { 0, 0, 0, 0 } };

    System.out.println(rowWithMax1s(mat));
}

}

Python

Function to find the index of the row containing the maximum number of 1s.

def rowWithMax1s(mat):

row_index = -1
max_count = 0

m = len(mat)
n = len(mat[0])

# Iterate through each row of the matrix
for i in range(m):
    
    count = 0
    
    # Iterate through each column in the current row
    for j in range(n):
        
        # If a 1 is found, increment the count for this specific row
        if mat[i][j] == 1:
            count += 1
            
    # If the current row has more 1s than our previously recorded maximum,
    # update the maximum count and store the current row index
    if count > max_count:
        max_count = count
        row_index = i

return row_index

if name == "main":

mat = [
    [0, 1, 1, 1],
    [0, 0, 1, 1],
    [1, 1, 1, 1],
    [0, 0, 0, 0]
]

print(rowWithMax1s(mat))

C#

using System;

public class GFG {

// Function to find the index of the row containing the maximum number of 1s.
static int rowWithMax1s(int[,] mat) {
    
    int rowIndex = -1;
    int maxCount = 0;
    
    int m = mat.GetLength(0);
    int n = mat.GetLength(1);

    // Iterate through each row of the matrix
    for (int i = 0; i < m; i++) {
        
        int count = 0;
        
        // Iterate through each column in the current row
        for (int j = 0; j < n; j++) {
            
            // If a 1 is found, increment the count for this specific row
            if (mat[i, j] == 1) {
                count++;
            }
        }
        
        // If the current row has more 1s than our previously recorded maximum,
        // update the maximum count and store the current row index
        if (count > maxCount) {
            maxCount = count;
            rowIndex = i;
        }
    }

    return rowIndex;
}

public static void Main(string[] args) {
    
    int[,] mat = {
        {0, 1, 1, 1},
        {0, 0, 1, 1},
        {1, 1, 1, 1},
        {0, 0, 0, 0}
    };

    Console.WriteLine(rowWithMax1s(mat));
}

}

JavaScript

// Function to find the index of the row containing the maximum number of 1s. function rowWithMax1s(mat) {

let rowIndex = -1;
let maxCount = 0;

let m = mat.length;
let n = mat[0].length;

// Iterate through each row of the matrix
for (let i = 0; i < m; i++) {
    
    let count = 0;
    
    // Iterate through each column in the current row
    for (let j = 0; j < n; j++) {
        
        // If a 1 is found, increment the count for this specific row
        if (mat[i][j] === 1) {
            count++;
        }
    }
    
    // If the current row has more 1s than our previously recorded maximum,
    // update the maximum count and store the current row index
    if (count > maxCount) {
        maxCount = count;
        rowIndex = i;
    }
}

return rowIndex;

}

// Driver code let mat = [ [0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0] ];

console.log(rowWithMax1s(mat));

`

[Better Approach] Using Binary Search - O(m * log(n)) Time O(1) Space:

The idea is to take advantage of the fact that each row is sorted. We use binary search (lower_bound )to find the first occurrence of 1 in each row. Once we get this index, the number of 1s in that row is calculated as the total number of columns minus the index of the first 1. We keep track of the row with the maximum count of 1s while traversing all rows.

**Working of approach:

Traverse each row and use lower_bound (binary search) to find the first occurrence of 1.

Row 2 has the maximum number of 1s, so return **index 2.

C++ `

#include #include using namespace std;

// Function to find the index of the row containing the maximum number of 1s. int rowWithMax1s(vector<vector>& mat) { int max_row_index = -1; int max = -1;

// Updated R to m and C to n
int m = mat.size();
int n = mat[0].size();

// Traverse each row one by one
for (int i = 0; i < m; i++) {
    
    // Find the index of the first '1' using lower_bound
    auto it = lower_bound(mat[i].begin(), mat[i].end(), 1);
    
    // Convert iterator to index
    int index = it - mat[i].begin();
    
    // If a '1' is found, calculate total 1s
    if (it != mat[i].end() && n - index > max) {
        max = n - index;
        max_row_index = i;
    }
}
return max_row_index;

}

//Driver Code int main() { vector<vector> mat = { { 0, 1, 1, 1 }, { 0, 0, 1, 1 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 } };

cout << rowWithMax1s(mat) << endl;

return 0;

}

Java

import java.util.*;

public class GfG { // Function to find the index of the row containing the maximum number of 1s. public static int rowWithMax1s(int[][] mat) { int max_row_index = -1; int max = -1;

    // Updated R to m and C to n
    int m = mat.length;
    int n = mat[0].length;
    
    // Traverse each row one by one
    for (int i = 0; i < m; i++) {
        
        // Find the index of the first '1' using lower_bound
        int index = lowerBound(mat[i], 1);
        
        // If a '1' is found, calculate total 1s
        if (index != -1 && n - index > max) {
            max = n - index;
            max_row_index = i;
        }
    }
    return max_row_index;
}

// Helper function to find lower bound
public static int lowerBound(int[] arr, int target) {
    int left = 0, right = arr.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] >= target) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    return left == arr.length ? -1 : left;
}

//Driver Code
public static void main(String[] args) {
    int[][] mat = {
        {0, 1, 1, 1},
        {0, 0, 1, 1},
        {1, 1, 1, 1},
        {0, 0, 0, 0}
    };
    
    System.out.println(rowWithMax1s(mat));
}

}

Python

def lower_bound(arr, target): left, right = 0, len(arr) while left < right: mid = left + (right - left) // 2 if arr[mid] >= target: right = mid else: left = mid + 1 return left if left < len(arr) else -1

Function to find the index of the row containing the maximum number of 1s.

def rowWithMax1s(mat): max_row_index = -1 max_count = -1

# Updated R to m and C to n
m = len(mat)
n = len(mat[0])

# Traverse each row one by one
for i in range(m):
    
    # Find the index of the first '1' using lower_bound
    index = lower_bound(mat[i], 1)
    
    # If a '1' is found, calculate total 1s
    if index!= -1 and n - index > max_count:
        max_count = n - index
        max_row_index = i
return max_row_index

#Driver Code if name == 'main': mat = [ [0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0] ]

print(rowWithMax1s(mat))

C#

using System; using System.Collections.Generic;

public class GfG { // Function to find the index of the row containing the maximum number of 1s. public static int rowWithMax1s(List<List> mat) { int max_row_index = -1; int max = -1;

    // Updated R to m and C to n
    int m = mat.Count;
    int n = mat[0].Count;
    
    // Traverse each row one by one
    for (int i = 0; i < m; i++)
    {
        
        // Find the index of the first '1' using binary search
        int index = BinarySearch(mat[i], 1);
        
        // If a '1' is found, calculate total 1s
        if (index!= -1 && n - index > max)
        {
            max = n - index;
            max_row_index = i;
        }
    }
    return max_row_index;
}

// Helper function to perform binary search
public static int BinarySearch(List<int> list, int target)
{
    int left = 0;
    int right = list.Count - 1;
    while (left <= right)
    {
        int mid = left + (right - left) / 2;
        if (list[mid] >= target)
        {
            if (mid == 0 || list[mid - 1] < target)
                return mid;
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }
    return -1;
}

//Driver Code
public static void Main()
{
    List<List<int>> mat = new List<List<int>>
    {
        new List<int> { 0, 1, 1, 1 },
        new List<int> { 0, 0, 1, 1 },
        new List<int> { 1, 1, 1, 1 },
        new List<int> { 0, 0, 0, 0 }
    };
    
    Console.WriteLine(rowWithMax1s(mat));
}

}

JavaScript

function rowWithMax1s(mat) { let max_row_index = -1; let max = -1;

// Updated R to m and C to n
let m = mat.length;
let n = mat[0].length;

// Traverse each row one by one
for (let i = 0; i < m; i++) {

    // Find the index of the first '1' using binary search
    let index = binarySearch(mat[i], 1);

    // If a '1' is found, calculate total 1s
    if (index!== -1 && n - index > max) {
        max = n - index;
        max_row_index = i;
    }
}
return max_row_index;

}

// Helper function to perform binary search function binarySearch(arr, target) { let left = 0; let right = arr.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (arr[mid] >= target) { if (mid === 0 || arr[mid - 1] < target) return mid; right = mid - 1; } else { left = mid + 1; } } return -1; }

//Driver Code let mat = [ [0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0] ];

console.log(rowWithMax1s(mat));

`

[Expected Approach] Traversal from top-right to outside the grid - O(m + n) Time and O(1) Space:

The idea is to use the sorted property of rows to avoid checking all elements.Start from the top-right cell(row = 0, col = n- 1) and store the ans = -1. If the value in the current cell is 1, update ans with the current row and move left. Otherwise, if the current cell is 0, move to the next row:

Continue, till we move outside the grid and return ans.

mat_2

C++ `

#include #include

using namespace std;

// Function to find the index of the row containing the maximum number of 1s. // starts from the top-right corner of the matrix. int rowWithMax1s(vector<vector>& mat) {

int maxRow = -1;

int R = mat.size();
int C = mat[0].size();

// Start from the top-right corner of the matrix
int row = 0;
int col = C - 1;

// Traverse while we are within the bounds of the matrix
while (row < R && col >= 0) {
    
    // If the current element is 0, it means there are no more 1s to the left.
    // We cannot find a better answer in this row, so we move down to the next row.
    if (mat[row][col] == 0) {
        row++;
    }
    
    // If the current element is 1, we update our answer to the current row.
    // Since the row is sorted, there might be more 1s to the left, so we move left.
    else {
        maxRow = row;
        col--;
    }
}

return maxRow;

}

int main() {

vector<vector<int>> mat = { 
    { 0, 1, 1, 1 },
    { 0, 0, 1, 1 },
    { 1, 1, 1, 1 },
    { 0, 0, 0, 0 } 
};

cout << rowWithMax1s(mat) << "\n";

return 0;

}

Java

class GFG {

// Function to find the index of the row containing the maximum number of 1s.
// Starts from the top-right corner of the matrix.
static int rowWithMax1s(int[][] mat) {
    
    int maxRow = -1;
    
    int R = mat.length;
    int C = mat[0].length;

    // Start from the top-right corner of the matrix
    int row = 0;
    int col = C - 1;

    // Traverse while we are within the bounds of the matrix
    while (row < R && col >= 0) {
        
        // If the current element is 0, this row cannot give us a better result.
        // Move down to the next row.
        if (mat[row][col] == 0) {
            row++;
        }
        
        // If the current element is 1, update the max row index.
        // To find if there are even more 1s in this row, move to the left.
        else {
            maxRow = row;
            col--;
        }
    }
    
    return maxRow;
}

public static void main(String[] args) {
    
    int[][] mat = { 
        { 0, 1, 1, 1 },
        { 0, 0, 1, 1 },
        { 1, 1, 1, 1 },
        { 0, 0, 0, 0 } 
    };

    System.out.println(rowWithMax1s(mat));
}

}

Python

Function to find the index of the row containing the maximum number of 1s.

Starts from the top-right corner of the matrix.

def rowWithMax1s(mat):

max_row = -1

R = len(mat)
C = len(mat[0])

# Start from the top-right corner of the matrix
row = 0
col = C - 1

# Traverse while we are within the bounds of the matrix
while row < R and col >= 0:
    
    # If the current element is 0, this row cannot give us a better result.
    # Move down to the next row.
    if mat[row][col] == 0:
        row += 1
        
    # If the current element is 1, update the max row index.
    # To find if there are even more 1s in this row, move to the left.
    else:
        max_row = row
        col -= 1
        
return max_row

if name == "main":

mat = [
    [0, 1, 1, 1],
    [0, 0, 1, 1],
    [1, 1, 1, 1],
    [0, 0, 0, 0]
]

print(rowWithMax1s(mat))

C#

using System;

public class GFG {

// Function to find the index of the row containing the maximum number of 1s.
// Starts from the top-right corner of the matrix.

static int RowWithMax1s(int[,] mat) {
    
    int maxRow = -1;
    
    // Dynamically determine the number of rows and columns from the input matrix
    int R = mat.GetLength(0);
    int C = mat.GetLength(1);

    // Start from the top-right corner of the matrix
    int row = 0;
    int col = C - 1;

    // Traverse while we are within the bounds of the matrix
    while (row < R && col >= 0) {
        
        // If the current element is 0, this row cannot give us a better result.
        // Move down to the next row.
        if (mat[row, col] == 0) {
            row++;
        }
        
        // If the current element is 1, update the max row index.
        // To find if there are even more 1s in this row, move to the left.
        else {
            maxRow = row;
            col--;
        }
    }
    
    return maxRow;
}

public static void Main(string[] args) {
    
    int[,] mat = { 
        { 0, 1, 1, 1 },
        { 0, 0, 1, 1 },
        { 1, 1, 1, 1 },
        { 0, 0, 0, 0 } 
    };

    Console.WriteLine(RowWithMax1s(mat));
}

}

JavaScript

// Function to find the index of the row containing the maximum number of 1s. // Starts from the top-right corner of the matrix. function rowWithMax1s(mat) {

let maxRow = -1;

let R = mat.length;
let C = mat[0].length;

// Start from the top-right corner of the matrix
let row = 0;
let col = C - 1;

// Traverse while we are within the bounds of the matrix
while (row < R && col >= 0) {
    
    // If the current element is 0, this row cannot give us a better result.
    // Move down to the next row.
    if (mat[row][col] === 0) {
        row++;
    }
    
    // If the current element is 1, update the max row index.
    // To find if there are even more 1s in this row, move to the left.
    else {
        maxRow = row;
        col--;
    }
}

return maxRow;

}

// Driver code let mat = [ [0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0] ];

console.log(rowWithMax1s(mat));

`