|
| 1 | +/** |
| 2 | + * 3044. Most Frequent Prime |
| 3 | + * https://leetcode.com/problems/most-frequent-prime/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a m x n 0-indexed 2D matrix mat. From every cell, you can create numbers |
| 7 | + * in the following way: |
| 8 | + * - There could be at most 8 paths from the cells namely: east, south-east, south, south-west, |
| 9 | + * west, north-west, north, and north-east. |
| 10 | + * - Select a path from them and append digits in this path to the number being formed by |
| 11 | + * traveling in this direction. |
| 12 | + * - Note that numbers are generated at every step, for example, if the digits along the path |
| 13 | + * are 1, 9, 1, then there will be three numbers generated along the way: 1, 19, 191. |
| 14 | + * |
| 15 | + * Return the most frequent prime number greater than 10 out of all the numbers created by |
| 16 | + * traversing the matrix or -1 if no such prime number exists. If there are multiple prime |
| 17 | + * numbers with the highest frequency, then return the largest among them. |
| 18 | + * |
| 19 | + * Note: It is invalid to change the direction during the move. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} mat |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var mostFrequentPrime = function(mat) { |
| 27 | + const m = mat.length; |
| 28 | + const n = mat[0].length; |
| 29 | + const frequency = new Map(); |
| 30 | + const directions = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]; |
| 31 | + |
| 32 | + const isPrime = num => { |
| 33 | + if (num <= 1) return false; |
| 34 | + for (let i = 2; i * i <= num; i++) { |
| 35 | + if (num % i === 0) return false; |
| 36 | + } |
| 37 | + return true; |
| 38 | + }; |
| 39 | + |
| 40 | + for (let i = 0; i < m; i++) { |
| 41 | + for (let j = 0; j < n; j++) { |
| 42 | + for (const [dx, dy] of directions) { |
| 43 | + let x = i; |
| 44 | + let y = j; |
| 45 | + let num = 0; |
| 46 | + while (x >= 0 && x < m && y >= 0 && y < n) { |
| 47 | + num = num * 10 + mat[x][y]; |
| 48 | + if (num > 10 && isPrime(num)) { |
| 49 | + frequency.set(num, (frequency.get(num) || 0) + 1); |
| 50 | + } |
| 51 | + x += dx; |
| 52 | + y += dy; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + let maxFreq = 0; |
| 59 | + let result = -1; |
| 60 | + for (const [num, freq] of frequency) { |
| 61 | + if (freq > maxFreq || (freq === maxFreq && num > result)) { |
| 62 | + maxFreq = freq; |
| 63 | + result = num; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return result; |
| 68 | +}; |
0 commit comments