Lucky Numbers in a Matrix in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Given a m * n matrix of distinct numbers, we have to return all lucky numbers in the 2-D array (matrix) in any order.

A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.

For example − If the input array is −

const arr = [
   [3,7,8],
   [9,11,13],
   [15,16,17]
];

Then the output should be −

const output = [15];

because 15 is the only lucky number since it is the minimum in its row and the maximum in its column.

Example

The code for this will be −

const arr = [
   [3,7,8],
   [9,11,13],
   [15,16,17]
];
const luckyNumbers = (arr, res = []) => {
   let M = arr.length, N = arr[0].length;
   let min = Array(M).fill( Infinity);
   let max = Array(N).fill(-Infinity);
   for (let i = 0; i < M; ++i)
   for (let j = 0; j < N; ++j)
   min[i] = Math.min(min[i], arr[i][j]),
   max[j] = Math.max(max[j], arr[i][j]);
   for (let i = 0; i < M; ++i)
   for (let j = 0; j < N; ++j)
   if (min[i] == max[j])
   res.push(arr[i][j]);
   return res;
};
console.log(luckyNumbers(arr));

Output

And the output in the console will be −

[15]
raja
Published on 25-Nov-2020 07:01:05
Advertisements