Skip to content

Commit 786daec

Browse files
committed
feat: Add solution for lucky-numbers-in-a-matrix problem
1 parent c1f98ee commit 786daec

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
const luckyNumbers = (matrix: number[][]): number[] => {
2+
const [rows, cols] = [matrix.length, matrix[0].length];
3+
const minRows: Record<number, [number, number]> = {};
4+
const maxCols: Record<number, [number, number]> = {};
5+
6+
for (let row = 0; row < rows; row++) {
7+
let minRowsVal: [number, number] = [10e5 + 1, -1];
8+
for (let col = 0; col < cols; col++) {
9+
const val = matrix[row][col];
10+
11+
if (val < minRowsVal[0]) {
12+
minRowsVal = [val, col];
13+
}
14+
15+
if (!(col in maxCols)) {
16+
maxCols[col] = [val, row];
17+
}
18+
19+
if (val > maxCols[col][0]) {
20+
maxCols[col] = [val, row];
21+
}
22+
}
23+
24+
minRows[row] = minRowsVal;
25+
}
26+
27+
const ans: number[] = [];
28+
29+
Object.entries(minRows).forEach(([row, [val, col]]) => {
30+
const [_, rowVal] = maxCols[col];
31+
32+
if (rowVal === Number(row)) ans.push(val);
33+
});
34+
35+
return ans;
36+
};
37+
38+
describe('Lucky Numbers in a Matrix', () => {
39+
it('#1 should return [15]', () => {
40+
expect(
41+
luckyNumbers([
42+
[3, 7, 8],
43+
[9, 11, 13],
44+
[15, 16, 17],
45+
])
46+
).toEqual([15]);
47+
});
48+
49+
it('#2 should return [12]', () => {
50+
expect(
51+
luckyNumbers([
52+
[1, 10, 4, 2],
53+
[9, 3, 8, 7],
54+
[15, 16, 17, 12],
55+
])
56+
).toEqual([12]);
57+
});
58+
59+
it('#3 should return [7]', () => {
60+
expect(
61+
luckyNumbers([
62+
[7, 8],
63+
[1, 2],
64+
])
65+
).toEqual([7]);
66+
});
67+
68+
it('#4 should return [1]', () => {
69+
expect(
70+
luckyNumbers([
71+
[1, 2],
72+
[3, 4],
73+
])
74+
).toEqual([3]);
75+
});
76+
77+
it('#5 should return [1]', () => {
78+
expect(luckyNumbers([[1, 2, 3]])).toEqual([1]);
79+
});
80+
});

0 commit comments

Comments
 (0)