Finding Lucky Numbers in a Matrix in JavaScript

In the given problem statement we have to write a function to get the lucky numbers in a matrix with the help of Javascript. So we will implement this task with for loops and functions of Javascript.

Understanding the problem statement

The problem statement is asking us to find the lucky numbers in a given matrix. So the lucky number will be defined as a number in the matrix which is the minimum value for its own row and the maximum value for its column. For example we have a matrix [ [3, 7], [9, 11] ], in this matrix the lucky number is [9] by following the terms for the lucky number.

Algorithm

Step 1 − Create a function and name it as luckyNumbers and pass an argument of matrix inside the function brackets.

Step 2 − Iterate over every row of the given matrix.

Step 3 − Find the smallest element and also its index for every row in the matrix.

Step 4 − Check if the smallest item's index is also the index of the maximum item in the column in which the minimum element is situated.

Step 5 − If the situation is true then the min item is the lucky number. So store it in an array.

Step 6 − Return the array of lucky numbers.

Code for the algorithm

//Function to find the lucky number in a given matrix
function luckyNumbers(matrix) {
const m = matrix.length;
const n = matrix[0].length;
const luckyNums = [];

for (let i = 0; i < m; i++) {
let minIndex = 0;
for (let j = 1; j < n; j++) {
if (matrix[i][j] < matrix[i][minIndex]) {
minIndex = j;
}
}
let maxIndex = 0;
for (let k = 1; k < m; k++) {
if (matrix[k][minIndex] > matrix[maxIndex][minIndex]) {
maxIndex = k;
}
}
if (maxIndex === i) {
luckyNums.push(matrix[i][minIndex]);
}
}

return luckyNums;
}
const matrix = [
[3, 7, 8],
[9, 11, 13],
[15, 16, 17]
];
console.log(luckyNumbers(matrix));


Complexity

The time complexity for the implemented function is O(m * n) in which m is the number of rows and n is the number of columns in the matrix. As we have iterated over each element in the matrix one time to find the minimum in each row and the maximum element in the corresponding column. And the space complexity for the code is O(k) in which k is the number of lucky numbers in the matrix.

Conclusion

In the function we iterated over each row of the matrix to find the minimum item and its index and then check if the minimum item's index is also of the maximum item in the column in which the minimum item is located. If the condition is true then the minimum item is a lucky number in the given matrix. The time complexity is O(m * n) and space complexity is O(k) and here k is the lucky number in the matrix.

Updated on: 18-May-2023

553 Views

Kickstart Your Career

Get certified by completing the course

Advertisements