Most Frequent Prime - Problem
Most Frequent Prime
You're given an
Here's the exciting part: as you travel in a chosen direction, you create multiple numbers at each step. For example, if you encounter digits
Your mission: Find the most frequent prime number greater than 10 from all possible paths. If multiple primes tie for highest frequency, return the largest one. If no such prime exists, return
Remember: Once you pick a direction, you must stick to it - no zigzagging allowed!
You're given an
m ร n 2D matrix of digits. Your task is to explore this matrix like a digital treasure hunter! From every cell, you can travel in any of the 8 directions (east, south-east, south, south-west, west, north-west, north, and north-east) and collect digits to form numbers.Here's the exciting part: as you travel in a chosen direction, you create multiple numbers at each step. For example, if you encounter digits
1, 9, 1 along your path, you generate three numbers: 1, 19, and 191.Your mission: Find the most frequent prime number greater than 10 from all possible paths. If multiple primes tie for highest frequency, return the largest one. If no such prime exists, return
-1.Remember: Once you pick a direction, you must stick to it - no zigzagging allowed!
Input & Output
example_1.py โ Basic Matrix
$
Input:
mat = [[1,1],[9,9],[1,1]]
โบ
Output:
19
๐ก Note:
From position (0,0), going south-east: 1โ19โ191. From position (1,0), going east: 9โ99. The prime 19 appears multiple times from different paths, making it the most frequent prime > 10.
example_2.py โ No Valid Primes
$
Input:
mat = [[1]]
โบ
Output:
-1
๐ก Note:
The only number we can generate is 1, which is not greater than 10, so we return -1.
example_3.py โ Tie-Breaking
$
Input:
mat = [[1,1],[1,2]]
โบ
Output:
11
๐ก Note:
Multiple primes might have the same frequency, but we return the largest one among those with the highest frequency. Here 11 is a prime that can be formed and is the answer.
Constraints
- m == mat.length
- n == mat[i].length
- 1 โค m, n โค 6
- 1 โค mat[i][j] โค 9
- Numbers can grow large during path traversal
Visualization
Tap to expand
Understanding the Visualization
1
Choose Starting Position
Start mining from any cell in the matrix
2
Pick Mining Direction
Choose one of 8 possible directions to mine
3
Collect Digits
As you mine deeper, collect digits to form numbers
4
Identify Prime Gems
Check if each number > 10 is a prime
5
Count Frequencies
Track how often each prime appears
6
Find Most Valuable
Return the most frequent prime (largest if tied)
Key Takeaway
๐ฏ Key Insight: By combining path generation with immediate prime checking and frequency tracking, we can solve this efficiently in one pass through the matrix, avoiding the need to store all generated numbers.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code