Most Frequent Prime

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
191Generated Numbers:1 (not > 10)19 (prime โœ“)191 (prime โœ“)Prime Frequency19: โ–ˆโ–ˆโ–ˆโ–ˆ (4 times)191: โ–ˆโ–ˆ (2 times)23: โ–ˆ (1 time)Winner: 19
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.7K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen