You are given an m x n 0-indexed 2D matrix mat. From every cell, you can create numbers by traveling in up to 8 directions: east, south-east, south, south-west, west, north-west, north, and north-east.

Select a path from any cell and append digits in this direction to form numbers. Numbers are generated at every step - for example, if digits along a path are 1, 9, 1, then three numbers are generated: 1, 19, and 191.

Return the most frequent prime number greater than 10 from all numbers created, or -1 if no such prime exists. If multiple primes have the highest frequency, return the largest among them.

Note: You cannot change direction during movement along a path.

Input & Output

Example 1 — Basic Matrix
$ Input: mat = [[1,1],[9,9]]
Output: 11
💡 Note: From cell (0,0): paths generate numbers 1, 11, 19, 99. From other cells we get similar numbers. Prime 11 appears most frequently in various directions.
Example 2 — No Valid Primes
$ Input: mat = [[1]]
Output: -1
💡 Note: Single cell can only generate number 1, which is not > 10, so no valid primes exist.
Example 3 — Multiple Directions
$ Input: mat = [[7,1,3],[9,7,1],[2,3,1]]
Output: 13
💡 Note: Various paths generate primes like 71, 13, 37. Prime 13 appears in multiple directions making it most frequent.

Constraints

  • 1 ≤ m, n ≤ 6
  • 1 ≤ mat[i][j] ≤ 9

Visualization

Tap to expand
Most Frequent Prime INPUT 2D Matrix (2x2) 1 1 9 9 8 Directions from each cell: N NE E SE S SW W NW mat = [[1,1],[9,9]] ALGORITHM STEPS 1 Traverse Matrix Visit each cell as start 2 Generate Numbers Follow 8 dirs, build nums 3 Check Prime If num > 10, check prime 4 Count Frequency Track prime occurrences Numbers Generated: From (0,0): 1, 11, 19, 191 From (0,1): 1, 11, 19, 199 From (1,0): 9, 91, 99, 911 From (1,1): 9, 91, 99, 919 Primes: 11, 19, 191, 199... FINAL RESULT Prime Frequency Count Prime Count 11 2 19 2 191 1 199 1 Both 11 and 19 have freq=2 Return larger if tie --> but 11 appears first, both max Output: 11 Key Insight: For each cell, explore all 8 directions without changing direction. Build numbers digit by digit (e.g., path 1-->9-->1 gives 1, 19, 191). Use efficient prime checking: only test divisors up to sqrt(n). TutorialsPoint - Most Frequent Prime | Optimized with Efficient Prime Checking
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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