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
valis on one of the diagonals ofnumsif there exists an integerifor whichnums[i][i] = valor anifor whichnums[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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code