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: Matrix Path Number Generation1199East: 9 → 99NE: 9 → 91SE: 9 → 99Prime Check Optimization:• Test only up to √n for divisors• Skip even numbers after 2• Early termination on overflow• Only store prime frequenciesResult: Most frequent prime > 10If tied frequency → return largest prime
Understanding the Visualization
1
Matrix Input
2D matrix with single digits
2
Path Exploration
Generate numbers by moving in 8 directions
3
Prime Frequency
Count prime numbers > 10 and return most frequent
Key Takeaway
🎯 Key Insight: Generate numbers incrementally in all 8 directions, using efficient prime checking to count frequencies
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