Prime In Diagonal - Problem

You are given a 0-indexed two-dimensional integer array nums.

Return the largest prime number that lies on at least one of the diagonals of nums. In case no prime is present on any of the diagonals, return 0.

Note that:

  • An integer is prime if it is greater than 1 and has no positive integer divisors other than 1 and itself.
  • An integer val is on one of the diagonals of nums if there exists an integer i for which nums[i][i] = val or an i for which nums[i][nums.length - i - 1] = val.

Input & Output

Example 1 — Basic Case
$ Input: nums = [[1,2,3],[5,5,6],[7,8,9]]
Output: 7
💡 Note: Main diagonal: [1,5,9], Anti-diagonal: [3,5,7]. Prime numbers: 3, 5, 7. Largest prime is 7.
Example 2 — No Primes
$ Input: nums = [[1,2,3],[5,6,7],[9,10,15]]
Output: 7
💡 Note: Main diagonal: [1,6,15], Anti-diagonal: [3,6,9]. Prime numbers: 3, 7. Wait - 7 is not on diagonal. Actually primes are just [3], so answer is 3.
Example 3 — All Non-Prime
$ Input: nums = [[1,2,3],[5,4,6],[7,8,9]]
Output: 7
💡 Note: Main diagonal: [1,4,9], Anti-diagonal: [3,4,7]. Prime numbers on diagonals: 3, 7. Largest is 7.

Constraints

  • 1 ≤ nums.length ≤ 300
  • nums.length == nums[i].length
  • 1 ≤ nums[i][j] ≤ 4*106

Visualization

Tap to expand
Prime In Diagonal: Find Largest Prime on Matrix Diagonals123556789Main Diagonal: [1, 5, 9]Anti-Diagonal: [3, 5, 7]All diagonal elements: [1, 5, 9, 3, 5, 7]Prime check: 3✓, 5✓, 7✓Result: 7 (largest prime)
Understanding the Visualization
1
Input Matrix
3x3 matrix with main and anti-diagonals highlighted
2
Extract Diagonals
Collect all elements from both diagonals
3
Find Max Prime
Check each diagonal element for primality, return largest
Key Takeaway
🎯 Key Insight: Only diagonal elements matter - check nums[i][i] and nums[i][n-1-i] for primes
Asked in
Amazon 12 Microsoft 8 Google 6
12.5K Views
Medium Frequency
~15 min Avg. Time
340 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