The Wayback Machine - https://web.archive.org/web/20240927182319/https://www.geeksforgeeks.org/find-the-row-with-maximum-number-1s/
Open In App

Find the row with maximum number of 1s

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
25.0%
64.9K

Given a binary 2D array, where each row is sorted. Find the row with the maximum number of 1s. 

Examples:  

Input matrix : 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 1s, that is 4.

Input matrix : 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 1s, that is 3.


[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 1s.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function that returns index of row with 
// maximum number of 1s.
int rowWithMax1s(vector<vector<bool>>& mat) {
    int rowIndex = -1;
    int maxCount = 0;
    int R = mat.size();
    int C = mat[0].size();

    for (int i = 0; i < R; i++) {
        int count = 0;
        for (int j = 0; j < C; j++) {
            if (mat[i][j] == 1) {
                count++;
            }
        }
        if (count > maxCount) {
            maxCount = count;
            rowIndex = i;
        }
    }

    return rowIndex;
}

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

    cout << rowWithMax1s(mat);
    return 0;
}
C
// C program to find the row with maximum number of 1s.
#include<stdio.h>
#include<stdbool.h>  

#define R 4
#define C 4

// Function that returns index of row
// with maximum number of 1s.
int rowWithMax1s(bool mat[R][C]) {
    int indexOfRowWithMax1s = -1 ;
    int maxCount = 0 ;
    
    // Visit each row.
    // Count number of 1s.
    /* If count is more that the maxCount then update the maxCount
    and store the index of current row in indexOfRowWithMax1s variable. */
    for(int i = 0 ; i < R ; i++){
        int count = 0 ;
        for(int j = 0 ; j < C ; j++ ){
            if(mat[i][j] == 1){
                count++ ;
            }
        }
        if(count > maxCount){
            maxCount = count ;
            indexOfRowWithMax1s = i ;
        }
    }
    
    return indexOfRowWithMax1s ;
}

 // Driver Code
int main()
{
    bool mat[R][C] = { {0, 0, 0, 1},
                    {0, 1, 1, 1},
                    {1, 1, 1, 1},
                    {0, 0, 0, 0}};

    int indexOfRowWithMax1s = rowWithMax1s(mat);
    printf("Index of row with maximum 1s is %d",indexOfRowWithMax1s);

    return 0;
}
Java
// Java program for the above approach
import java.util.*;

class GFG {

static int R = 4 ;
static int C = 4 ;

// Function that returns index of row
// with maximum number of 1s.
static int rowWithMax1s(int mat[][], int R, int C)
{
    // Flag to check if there is not even a single 1 in the matrix.  
      boolean flag = true;
    // Initialize max values
    int max_row_index = 0, max_ones = 0;;

    // Traverse for each row and count number of 1s
    for(int i = 0 ; i < R ; i++){

            int count1 = 0 ;
            for(int j = 0 ; j < C ; j++){
                if(mat[i][j] == 1){
                    count1++;
                    flag = false;
                }
            }
            if(count1>max_ones){
                max_ones = count1;
                max_row_index = i;
            }

        }
      // Edge case where there are no 1 in the matrix
      if(flag){
            return -1;
        }

    return max_row_index;
}

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

    System.out.print("Index of row with maximum 1s is " + rowWithMax1s(mat,R,C));
    }
}
Python
# Python implementation of the approach
R,C = 4,4

# Function to find the index of first index 
# of 1 in a boolean array arr 
def first(arr , low , high): 

    if(high >= low): 

        # Get the middle index 
        mid = low + (high - low)//2 
    
        # Check if the element at middle index is first 1 
        if ( ( mid == 0 or arr[mid-1] == 0) and arr[mid] == 1): 
            return mid 
    
        # If the element is 0, recur for right side 
        elif (arr[mid] == 0): 
            return first(arr, (mid + 1), high); 
        
        # If element is not first 1, recur for left side 
        else:
            return first(arr, low, (mid -1)); 

    return -1 

# Function that returns index of row 
# with maximum number of 1s. 
def rowWithMax1s(mat): 

    # Initialize max values 
    max_row_index,Max = 0,-1 

    # Traverse for each row and count number of 1s 
    # by finding the index of first 1 
    for i in range(R):

        index = first (mat[i], 0, C-1)
        if (index != -1 and C-index > Max):
            Max = C - index; 
            max_row_index = i

    return max_row_index 

# Driver Code
mat = [[0, 0, 0, 1], 
       [0, 1, 1, 1], 
       [1, 1, 1, 1], 
       [0, 0, 0, 0]]
print("Index of row with maximum 1s is " + str(rowWithMax1s(mat)))
C#
// C# program for the above approach
using System;
using System.Collections.Generic;

public class GFG {

  static int R = 4;
  static int C = 4;

  // Function to find the index of first index
  // of 1 in a bool array []arr
  static int first(int []arr, int low, int high) {
    if (high >= low) 
    {

      // Get the middle index
      int mid = low + (high - low) / 2;

      // Check if the element at middle index is first 1
      if ((mid == 0 || arr[mid - 1] == 0) && arr[mid] == 1)
        return mid;

      // If the element is 0, recur for right side
      else if (arr[mid] == 0)
        return first(arr, (mid + 1), high);

      // If element is not first 1, recur for left side
      else
        return first(arr, low, (mid - 1));
    }
    return -1;
  }
  public static int[] GetRow(int[,] matrix, int row)
  {
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];

    for (var i = 0; i < rowLength; i++)
      rowVector[i] = matrix[row, i];

    return rowVector;
  }

  // Function that returns index of row
  // with maximum number of 1s.
  static int rowWithMax1s(int [,]mat)
  {

    // Initialize max values
    int max_row_index = 0, max = -1;

    // Traverse for each row and count number of 1s
    // by finding the index of first 1
    int i, index;
    for (i = 0; i < R; i++) {
      int []row = GetRow(mat,i);
      index = first(row, 0, C - 1);
      if (index != -1 && C - index > max) {
        max = C - index;
        max_row_index = i;
      }
    }

    return max_row_index;
  }

  // Driver Code
  public static void Main(String[] args) {

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

    Console.Write("Index of row with maximum 1s is " + rowWithMax1s(mat));

  }
}
JavaScript
// javascript program for the above approach

var R = 4;
var C = 4;

// Function to find the index of first index 
// of 1 in a boolean array arr 
function first(arr, low, high) {
    if (high >= low) {
        // Get the middle index 
        var mid = low + parseInt((high - low) / 2);

        // Check if the element at middle index is first 1 
        if ((mid == 0 || arr[mid - 1] == 0) && arr[mid] == 1)
            return mid;

        // If the element is 0, recur for right side 
        else if (arr[mid] == 0)
            return first(arr, (mid + 1), high);

        // If element is not first 1, recur for left side 
        else
            return first(arr, low, (mid - 1));
    }
    return -1;
}

// Function that returns index of row 
// with maximum number of 1s. 
function rowWithMax1s(mat) {

    // Initialize max values 
    var max_row_index = 0,
        max = -1;

    // Traverse for each row and count number of 1s 
    // by finding the index of first 1 
    var i, index;
    for (i = 0; i < R; i++) {
        index = first(mat[i], 0, C - 1);
        if (index != -1 && C - index > max) {
            max = C - index;
            max_row_index = i;
        }
    }
    return max_row_index;
}

// Driver Code
var mat = [
    [0, 0, 0, 1],
    [0, 1, 1, 1],
    [1, 1, 1, 1],
    [0, 0, 0, 0]
];
console.log("Index of row with maximum 1s is " + rowWithMax1s(mat));

Output
2

Time Complexity:  O(M*N), where M is the number of rows and N is the number of columns.
Auxiliary Space:  O(1)

[Better Approach] Using Binary Search – O(M * logN) Time O(1) Space:

Since each row is sorted, we can use Binary Search to count 1s in each row. We find the index of the first occurrence of 1 in each row. The count of 1s will be equal to the total number of columns minus the index of the first 1.

Below is the implementation of the above approach: 

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the index of first instance
// of 1 in a boolean array arr[]
int first(vector<bool>& arr, int low, int high) {
    int idx = -1;
    while (low <= high) {
      
        // Get the middle index
        int mid = low + (high - low) / 2;

        // If the element at mid is 1, then update mid as
        // starting index of 1s and search in the left half
        if (arr[mid] == 1) {
            idx = mid;
            high = mid - 1;
        }
      
        // If the element at mid is 0, then search in the
        // right half
        else {
            low = mid + 1;
        }
    }
    return idx;
}

// Function that returns index of row
// with maximum number of 1s.
int rowWithMax1s(vector<vector<bool>>& mat) {
    // Initialize max values
    int max_row_index = -1, max = -1;
    int R = mat.size();
    int C = mat[0].size();

    // Traverse for each row and count number of 1s
    // by finding the index of first 1
    for (int i = 0; i < R; i++) {
        int index = first(mat[i], 0, C - 1);
        if (index != -1 && C - index > max) {
            max = C - index;
            max_row_index = i;
        }
    }

    return max_row_index;
}

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

    cout << rowWithMax1s(mat);

    return 0;
}
C
// CPP program to find the row
// with maximum number of 1s
#include <stdio.h>
using namespace std;
#define R 4
#define C 4

// Function to find the index of first instance
// of 1 in a boolean array arr[]
int first(bool arr[], int low, int high)
{
    int idx = -1;
    while (low <= high) {
        // Get the middle index
        int mid = low + (high - low) / 2;

        // If the element at mid is 1, then update mid as
        // starting index of 1s and search in the left half
        if (arr[mid] == 1) {
            idx = mid;
            high = mid - 1;
        }
        // If the element at mid is 0, then search in the
        // right half
        else {
            low = mid + 1;
        }
    }
    return idx;
}

// Function that returns index of row
// with maximum number of 1s.
int rowWithMax1s(bool mat[R][C])
{
    // Initialize max values
    int max_row_index = 0, max = -1;

    // Traverse for each row and count number of 1s
    // by finding the index of first 1
    int i, index;
    for (i = 0; i < R; i++) {
        index = first(mat[i], 0, C - 1);
        if (index != -1 && C - index > max) {
            max = C - index;
            max_row_index = i;
        }
    }

    return max_row_index;
}

// Driver Code
int main()
{
    bool mat[R][C] = { { 0, 0, 0, 1 },
                       { 0, 1, 1, 1 },
                       { 1, 1, 1, 1 },
                       { 0, 0, 0, 0 } };

    printf("Index of row with maximum 1s is %d",
           rowWithMax1s(mat));

    return 0;
}
Java
// Java program to find the row
// with maximum number of 1s
import java.io.*;

class GFG {
    static int R = 4, C = 4;
    // Function to find the index of first index
    // of 1 in a boolean array arr[]
    static int first(int arr[], int low, int high)
    {
        int idx = -1;
        while (low <= high) {
            // Get the middle index
            int mid = low + (high - low) / 2;

            // If the element at mid is 1, then update mid
            // as starting index of 1s and search in the
            // left half
            if (arr[mid] == 1) {
                idx = mid;
                high = mid - 1;
            }
            // If the element at mid is 0, then search in
            // the right half
            else {
                low = mid + 1;
            }
        }
        return idx;
    }

    // Function that returns index of row
    // with maximum number of 1s.
    static int rowWithMax1s(int mat[][])
    {
        // Initialize max values
        int max_row_index = 0, max = -1;

        // Traverse for each row and count number of
        // 1s by finding the index of first 1
        int i, index;
        for (i = 0; i < R; i++) {
            index = first(mat[i], 0, C - 1);
            if (index != -1 && C - index > max) {
                max = C - index;
                max_row_index = i;
            }
        }

        return max_row_index;
    }
    // Driver Code
    public static void main(String[] args)
    {
        int mat[][] = { { 0, 0, 0, 1 },
                        { 0, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 0, 0, 0, 0 } };
        System.out.println(
            "Index of row with maximum 1s is "
            + rowWithMax1s(mat));
    }
}
Python
# Python3 program to find the row
# with maximum number of 1s

# Function to find the index
# of first index of 1 in a
# boolean array arr[]


def first(arr, low, high):
    idx = -1
    while low <= high:
        # Get the middle index
        mid = low + (high - low) // 2

        # If the element at mid is 1, then update mid as
        # starting index of 1s and search in the left half
        if arr[mid] == 1:
            idx = mid
            high = mid - 1
        # If the element at mid is 0, then search in the
        # right half
        else:
            low = mid + 1
    return idx


# Function that returns
# index of row with maximum
# number of 1s.
def rowWithMax1s(mat):

    # Initialize max values
    R = len(mat)
    C = len(mat[0])
    max_row_index = 0
    max = -1

    # Traverse for each row and
    # count number of 1s by finding
    #  the index of first 1
    for i in range(0, R):
        index = first(mat[i], 0, C - 1)
        if index != -1 and C - index > max:
            max = C - index
            max_row_index = i

    return max_row_index


# Driver Code
mat = [[0, 0, 0, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 0, 0, 0]]
print("Index of row with maximum 1s is",
      rowWithMax1s(mat))
C#
// C# program to find the row with maximum
// number of 1s
using System;

class GFG {
    public static int R = 4, C = 4;

    // Function to find the index of first index
    // of 1 in a boolean array arr[]
    static int first(int[] arr, int low, int high)
    {
        int idx = -1;
        while (low <= high) {
            // Get the middle index
            int mid = low + (high - low) / 2;

            // If the element at mid is 1, then update mid
            // as starting index of 1s and search in the
            // left half
            if (arr[mid] == 1) {
                idx = mid;
                high = mid - 1;
            }
            // If the element at mid is 0, then search in
            // the right half
            else {
                low = mid + 1;
            }
        }
        return idx;
    }

    // Function that returns index of row
    // with maximum number of 1s.
    public static int rowWithMax1s(int[][] mat)
    {
        // Initialize max values
        int max_row_index = 0, max = -1;

        // Traverse for each row and count number
        // of 1s by finding the index of first 1
        int i, index;
        for (i = 0; i < R; i++) {
            index = first(mat[i], 0, C - 1);
            if (index != -1 && C - index > max) {
                max = C - index;
                max_row_index = i;
            }
        }

        return max_row_index;
    }

    // Driver Code
    public static void Main(string[] args)
    {
        int[][] mat
            = new int[][] { new int[] { 0, 0, 0, 1 },
                            new int[] { 0, 1, 1, 1 },
                            new int[] { 1, 1, 1, 1 },
                            new int[] { 0, 0, 0, 0 } };
        Console.WriteLine("Index of row with maximum 1s is "
                          + rowWithMax1s(mat));
    }
}
JavaScript
// JavaScript program to find the row
// with maximum number of 1s

R = 4
C = 4

// Function to find the index of first instance of 1 in an array arr[]
function first(arr, low, high) {
    let idx = -1;
    while (low <= high) {
        // Get the middle index
        let mid = Math.floor(low + (high - low) / 2);

        // If the element at mid is 1, then update mid as
        // starting index of 1s and search in the left half
        if (arr[mid] === 1) {
            idx = mid;
            high = mid - 1;
        }
        // If the element at mid is 0, then search in the right half
        else {
            low = mid + 1;
        }
    }
    return idx;
}

// Function that returns index of row
// with maximum number of 1s.
const rowWithMax1s = (mat) => {
    // Initialize max values
    let max_row_index = 0,
        max = -1;

    // Traverse for each row and count number of 1s
    // by finding the index of first 1
    let i, index;
    for (i = 0; i < R; i++) {
        index = first(mat[i], 0, C - 1);
        if (index != -1 && C - index > max) {
            max = C - index;
            max_row_index = i;
        }
    }

    return max_row_index;
}

// Driver Code

let mat = [
    [0, 0, 0, 1],
    [0, 1, 1, 1],
    [1, 1, 1, 1],
    [0, 0, 0, 0]
];

console.log(`Index of row with maximum 1s is ${rowWithMax1s(mat)}`);

Output
2

Time Complexity: O(M log N) where M is the number of rows and N is the number of columns in the matrix.
Auxiliary Space:  O(1)

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

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:

  • If mat[row][col] == 1, update ans = row and move left by col = col – 1.
  • Else if mat[row][col] == 0, row = row + 1.

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

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// The main function that returns index of row with maximum
// number of 1s.
int rowWithMax1s(vector<vector<bool>>& mat) {
    int maxRow = -1, row = 0;
    int R = mat.size();
    int C = mat[0].size();
    int col = C - 1;

    // Move till we are inside the matrix
    while (row < R && col >= 0) {
        // If the current value is 0, move down to the next row
        if (mat[row][col] == 0) {
            row += 1;
        }
        // Else if the current value is 1, update ans and
        // move to the left column
        else {
            maxRow = row;
            col -= 1;
        }
    }
    return maxRow;
}

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

    cout << "Index of row with maximum 1s is "
         << rowWithMax1s(mat);

    return 0;
}
C
// C++ program to find the row with maximum
// number of 1s
#include <stdio.h>
#include <stdbool.h>
#define R 4
#define C 4

// The main function that returns index of row with maximum
// number of 1s.
int rowWithMax1s(bool mat[R][C])
{
    int maxRow = -1, row = 0, col = C - 1;

    // Move till we are inside the matrix
    while (row < R && col >= 0) {
        // If the current value is 0, move down to the next
        // row
        if (mat[row][col] == 0) {
            row += 1;
        }
        // Else if the current value is 1, update ans and
        // move to the left column
        else {
            maxRow = row;
            col -= 1;
        }
    }
    return maxRow;
}

// Driver Code
int main()
{
    bool mat[R][C] = { { 0, 0, 0, 1 },
                       { 0, 1, 1, 1 },
                       { 1, 1, 1, 1 },
                       { 0, 0, 0, 0 } };

    printf("%d", rowWithMax1s(mat));

    return 0;
}
Java
public class GFG {
    static final int R = 4;
    static final int C = 4;

    // The main function that returns index of row with
    // maximum number of 1s
    public static int rowWithMax1s(int[][] mat)
    {
        int maxRow = -1, row = 0, col = C - 1;

        // Move till we are inside the matrix
        while (row < R && col >= 0) {
            // If the current value is 0, move down to the
            // next row
            if (mat[row][col] == 0) {
                row++;
            }
            // Else if the current value is 1, update maxRow
            // and move to the left column
            else {
                maxRow = row;
                col--;
            }
        }
        return maxRow;
    }

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

        System.out.println(
            "Index of row with maximum 1s is "
            + rowWithMax1s(mat));
    }
}
Python
# Python3 program to find the row
# with maximum number of 1s

# Function that returns
# index of row with maximum
# number of 1s.
def rowWithMax1s(mat):
    R = len(mat)
    C = len(mat[0])
    max_row = -1
    row = 0
    col = C - 1

    # Move till we are inside the matrix
    while row < R and col >= 0:
        # If the current value is 0, move down to the next row
        if mat[row][col] == 0:
            row += 1
        # Else if the current value is 1, update max_row and move to the left column
        else:
            max_row = row
            col -= 1

    return max_row


# Driver Code
mat = [[0, 0, 0, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 0, 0, 0]]
print("Index of row with maximum 1s is",
      rowWithMax1s(mat))
C#
using System;

public class GFG {
    static int R = 4;
    static int C = 4;

    // The main function that returns index of row with
    // maximum number of 1s
    static int RowWithMax1s(int[, ] mat)
    {
        int maxRow = -1, row = 0, col = C - 1;

        // Move till we are inside the matrix
        while (row < R && col >= 0) {
            // If the current value is 0, move down to the
            // next row
            if (mat[row, col] == 0) {
                row++;
            }
            // Else if the current value is 1, update maxRow
            // and move to the left column
            else {
                maxRow = row;
                col--;
            }
        }
        return maxRow;
    }

    // Driver Code
    static void Main()
    {
        int[, ] mat = { { 0, 0, 0, 1 },
                        { 0, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 0, 0, 0, 0 } };

        Console.WriteLine("Index of row with maximum 1s is "
                          + RowWithMax1s(mat));
    }
}
JavaScript
// Function that returns index of row with maximum number of 1s
function rowWithMax1s(mat) {
    const R = mat.length; // Number of rows
    const C = mat[0].length; // Number of columns

    let maxRow = -1;
    let row = 0;
    let col = C - 1;

    // Move until we are inside the matrix
    while (row < R && col >= 0) {
        // If the current value is 0, move down to the next row
        if (mat[row][col] === 0) {
            row++;
        }
        // Else if the current value is 1, update maxRow and move to the left column
        else {
            maxRow = row;
            col--;
        }
    }
    return maxRow;
}

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

console.log("Index of row with maximum 1s is", rowWithMax1s(mat));

Output
Index of row with maximum 1s is 2

Time Complexity: O(M+N) where M is the number of rows and N is the number of columns in the matrix.
Auxiliary Space:  O(1)



Similar Reads

Maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row
Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves from a cell (i, j) (i+1, j)(i+1, j-1)(i+1, j+1)Starting from any column in row 0, return the largest sum of any of the paths up to row N-1. Examples: Input : mat[4][4] = { {4, 2, 3, 4}, {2, 9, 1, 10}, {15, 1, 3, 0}, {16, 92, 41, 44} };Output :120path : 4 + 9 +
15+ min read
Find row and column pair in given Matrix with equal row and column sum
Given a matrix Mat of size N x M, the task is to find all the pairs of rows and columns where the sum of elements in the row is equal to the sum of elements in the columns. Examples: Input: M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}}Output: {{1, 1}}Explanation: The sum of elements of rows and columns of matrix M are: C = 1C = 2C = 3Sum of RowsR = 11225R
8 min read
Find row number of a binary matrix having maximum number of 1s
Given a binary matrix (containing only 0 and 1) of order n×n. All rows are sorted already, We need to find the row number with the maximum number of 1s. Also, find the number 1 in that row. Note: in case of a tie, print the smaller row number. Examples : Input : mat[3][3] = {0, 0, 1, 0, 1, 1, 0, 0, 0} Output : Row number = 2, MaxCount = 2 Input : m
14 min read
Check if any row of the matrix can be converted to the elements present in the target row
Given a matrix mat[][] of dimensions N*M and an array target[] of M integers, the task is to check whether any row of the matrix can be made equal to the array target[] by choosing any two rows of the matrix and update each element of any of the row to the maximum of elements at corresponding indices of the two chosen row. If it is possible to do s
7 min read
Print all possible paths from the first row to the last row in a 2D array
Given a 2D array of characters with M rows and N columns. The task is to print all the possible paths from top (first row) to bottom (last row). Examples: Input: arr[][] = { {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}} Output: adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfiInput: arr
7 min read
Replace diagonal elements in each row of given Matrix by Kth smallest element of that row
Given a matrix mat[ ][ ] of size N*N and an integer K, containing integer values, the task is to replace diagonal elements by the Kth smallest element of row. Examples: Input: mat[][]= {{1, 2, 3, 4} {4, 2, 7, 6} {3, 5, 1, 9} {2, 4, 6, 8}}K = 2Output: 2, 2, 3, 4 4, 4, 7, 6 3, 5, 3, 8 2, 4, 6, 4Explanation: 2nd smallest element of 1st row = 22nd smal
6 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
Find row with maximum and minimum number of zeroes in given Matrix
Given a 2D matrix containing only zeroes and ones, where each row is sorted. The task is to find the row with the maximum number of 0s and the row with minimum number of 0s.Example: Input: mat[][] = { {0, 1, 1, 1}, {0, 0, 1, 1}, {1, 1, 1, 1}, {0, 0, 0, 0}} Output: Row with min zeroes: 3 Row with max zeroes: 4Input: mat[][] = { {0, 1, 1, 1}, {0, 0,
11 min read
Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum eleme
6 min read
Find row with maximum sum in a Matrix
Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Row 3 has max sum 35 Input : mat[][] = { { 1, 2, 3 }, { 4, 2, 1 }, { 5, 6, 7 },
11 min read
Find maximum sum from top to bottom row with no adjacent diagonal elements
Given a matrix A[][] of N * M, the task is to find the maximum sum from the top row to the bottom row after selecting one element from each row with no adjacent diagonal element. Examples: Input: A = { {1, 2, 3, 4}, {8, 7, 6, 5}, {10, 11, 12, 13} } Output: 25 Explanation: Selected elements to give maximum sum - Row 0 = 4 Row 1 = 8 Row 2 = 13 Sum =
8 min read
Find the row whose product has maximum count of prime factors
Given a matrix of size N x M, the task is to print the elements of the row whose product has a maximum count of prime factors.Examples: Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output: 7 8 9 Explanation: Row 1: (1, 2, 3) has product 6 and it has 2 prime factors. Row 2: (4, 5, 6) has product 120 and it has 3 prime factors. Row 3: (7, 8, 9
11 min read
Find all matrix elements which are minimum in their row and maximum in their column
Given a matrix mat[][] of size M * N, the task is to find all matrix elements which are minimum in their respective row and maximum in their respective column. If no such element is present, print -1. Examples: Input: mat[][] = {{1, 10, 4}, {9, 3, 8}, {15, 16, 17}}Output: 15Explanation:15 is the only element which is maximum in its column {1, 9, 15
7 min read
Find the row with maximum unique elements in given Matrix
Given a matrix arr[][] of size N*M The task is to find the index of the row that has the maximum unique elements. If there are multiple rows possible, return the minimum indexed row. Examples: Input: arr[][] = { {1, 2, 3, 4, 5}, {1, 2, 2, 4, 7}, {1, 3, 1, 3, 1} } Output: 0Explanation: Rows 0, 1 & 2 have 5, 4 & 2 unique elements respectively
5 min read
Find and remove maximum value in each row of a given Matrix
Given a matrix mat[][] of size N * M, the task is to find and remove the maximum of each row from the matrix and add the largest among them and return the final sum. Perform these operations till the matrix becomes empty. Examples: Input: M = 3, N = 2, mat[][] = [[1, 2, 4], [3, 3, 1]]Output: 8Explanation: In the first operation, we remove 4 from th
5 min read
Javascript Program to Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21]Output :3976Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]Output :216556Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum element. Finall
2 min read
Queries to find number of indexes where characters repeated twice in row in substring L to R
Given string S of size N consisting of lower case characters and 2d array Q[][2] of size M representing several queries of type {L, R} representing a range. The task for this problem is for each query {L, R} to find several indexes where characters are repeated twice in a row in substring L to R. Examples: Input: S = "mississippi", Q[][2] = {{3, 9}
10 min read
Maximum sum of elements from each row in the matrix
Given a matrix, find the maximum sum we can have by selecting just one element from every row. Condition is element selected from nth row must be strictly greater than element from (n-1)th row, else no element must be taken from row. Print the sum if possible else print -1. Examples : Input : 1 2 31 2 37 8 9 Output : 14 (2 + 3 + 9) (values we are a
7 min read
Maximum cost path in an Undirected Graph such that no edge is visited twice in a row
Given an undirected graph having N vertices and M edges and each vertex is associated with a cost and a source vertex S is given. The task is to find the maximum cost path from source vertex S such that no edge is visited consecutively 2 or more times. Examples: Input: N = 5, M = 5, source = 1, cost[] = {2, 2, 8, 6, 9}, Below is the given graph: Ou
12 min read
Maximum sum of a Matrix where each value is from a unique row and column
Given a matrix of size N X N, the task is to find maximum sum of this Matrix where each value picked is from a unique column for every row.Examples: Input: matrix = [[3, 4, 4, 4], [1, 3, 4, 4], [3, 2, 3, 4], [4, 4, 4, 4]] Output: 16 Explanation: Selecting (0, 1) from row 1 = 4 Selecting (1, 2) from row 2 = 4 Selecting (2, 3) from row 3 = 4 Selectin
8 min read
Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
Given a matrix mat[][] whose elements are sorted both row-wise and column-wise. The task is to find the maximum sum of any submatrix from the given matrix mat[][]. Examples: Input: mat[][] = { {-6, -4, -1}, {-3, 2, 4}, {2, 5, 8}} Output: 19 Explanation: The largest submatrix is given by: 2 4 5 8Input: mat[][] = { {-4, -3}, {-2, -1} } Output: -1 Exp
10 min read
Maximum path sum when at most K elements can be picked from a row
Given a matrix mat[][] of size N * M and an integer K, the task is to find a path from the top-left cell (0, 0) to the bottom-right cell (N–1, M–1) of the given matrix such that: One right and downward movement are allowed. i.e., from (i, j) to (i, j-1) and (i+1, j). Sum of the elements in the path is maximum and not more than K cells can be chosen
14 min read
Maximum weight path ending at any element of last row in a matrix
Given a matrix of integers where every element represents the weight of the cell. Find the path having the maximum weight in matrix [N X N]. Path Traversal Rules are: It should begin from top left element.The path can end at any element of last row.We can move to follow two cells from a cell (i, j). Down Move : (i+1, j)Diagonal Move : (i+1, j+1) Ex
15 min read
Replace every matrix element with maximum of GCD of row or column
Given a matrix of n rows and m columns. The task is to replace each matrix element with Greatest Common Divisor of its row or column, whichever is maximum. That is, for each element (i, j) replace it from GCD of i'th row or GCD of j'th row, whichever is greater. Examples : Input : mat[3][4] = {1, 2, 3, 3, 4, 5, 6, 6 7, 8, 9, 9} Output : 1 1 3 3 1 1
7 min read
Check whether row or column swaps produce maximum size binary sub-matrix with all 1s
Given a binary matrix, the task is to find whether row swaps or column swaps give maximum size sub-matrix with all 1's. In a row swap, we are allowed to swap any two rows. In a column swap, we are allowed to swap any two columns. Output "Row Swap" or "Column Swap" and the maximum size. Examples: Input : 1 1 1 1 0 1 Output : Column Swap 4 By swappin
13 min read
Maximum XOR value of maximum and second maximum element among all possible subarrays
Given an array arr[] of N distinct positive integers, let's denote max(i, j) and secondMax(i, j) as the maximum and the second maximum element of the subarray arr[i...j]. The task is to find the maximum value of max(i, j) XOR secondMax(i, j) for all possible values of i and j. Note that the size of the subarray must be at least two.Examples: Input:
5 min read
Find the element at R'th row and C'th column in given a 2D pattern
Given two integers R and C, the task is to find the element at the Rth row and Cth column.Pattern: First Element of ith row =[Tex]\frac{i*(i-1)}{2} + 1[/Tex]Every element is a Arithmetic progression increasing difference where common difference is 1.Initial Difference Term = [Tex]i + 1[/Tex] Examples: Input: R = 4, C = 4 Output: 25 Explanation: Pat
5 min read
Program to find the Sum of each Row and each Column of a Matrix
Given a matrix of order m×n, the task is to find out the sum of each row and each column of a matrix. Examples: Input: array[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; Output: Sum of the 0 row is = 4 Sum of the 1 row is = 8 Sum of the 2 row is = 12 Sum of the 3 row is = 16 Sum of the 0 column is = 10 Sum of the 1 column is =
9 min read
Find the side of the squares which are inclined diagonally and lined in a row
Given here are n squares which are inclined and touch each other externally at vertices, and are lined up in a row.The distance between the centers of the first and last square is given.The squares have equal side length.The task is to find the side of each square.Examples: Input :d = 42, n = 4 Output :The side of each square is 9.899Input :d = 54,
4 min read
Find the original matrix when largest element in a row and a column are given
Given two arrays A[] and B[] of N and M integers respectively. Also given is a N X M binary matrix where 1 indicates that there was a positive integer in the original matrix and 0 indicates that the position is filled with 0 in the original matrix. The task is to form back the original matrix such that A[i] indicates the largest element in the ith
6 min read