Counting largest numbers in row and column in 2-D array in JavaScript

We are required to write a JavaScript function that takes in a two-dimensional array of integers as the only argument.

The task of our function is to calculate the count of all such integers from the array that are the greatest both within their row and the column.

The function should then return that count.

For example −

If the input array is −

const arr = [
   [21, 23, 22],
   [26, 26, 25],
   [21, 25, 27]
];

Then the output should be −

const output = 3;

because those three numbers are 26, 26, 27

Algorithm Explanation

The algorithm works by first finding the maximum value in each row and column, then counting elements that are maximum in both their row and column:

  1. Calculate the maximum value for each row
  2. Calculate the maximum value for each column
  3. Count elements that equal both their row maximum and column maximum

Example

Following is the code −

const arr = [
   [21, 23, 22],
   [26, 26, 25],
   [21, 25, 27]
];

const countGreatest = (matrix = []) => {
   let rows = matrix.length;
   if (rows == 0){
      return 0;
   };
   let cols = matrix[0].length;
   const colMax = [];
   const rowMax = [];
   let res = 0;
   
   // Find maximum in each row and column
   for (let r = 0; r 

Output

Following is the console output −

3

Step-by-Step Breakdown

Let's trace through the example:

const matrix = [
   [21, 23, 22],
   [26, 26, 25],
   [21, 25, 27]
];

// Row maximums: [23, 26, 27]
// Column maximums: [26, 26, 27]

// Check each element:
// matrix[1][0] = 26 (row max: 26, col max: 26) ?
// matrix[1][1] = 26 (row max: 26, col max: 26) ?  
// matrix[2][2] = 27 (row max: 27, col max: 27) ?

console.log("Row maximums:", [23, 26, 27]);
console.log("Column maximums:", [26, 26, 27]);
console.log("Count of elements that are both row and column maximum:", 3);
Row maximums: [ 23, 26, 27 ]
Column maximums: [ 26, 26, 27 ]
Count of elements that are both row and column maximum: 3

Conclusion

This algorithm efficiently finds elements that are simultaneously the maximum in their row and column by precomputing all row and column maximums, then comparing each element against both values. The time complexity is O(m×n) where m and n are the matrix dimensions.

Updated on: 2026-03-15T23:19:00+05:30

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements