Prime In Diagonal - Problem
You are given a 2D square matrix of integers. Your mission is to find the largest prime number that appears on either of the matrix's two main diagonals.
The Two Diagonals:
- Main diagonal: Elements where
row == column(top-left to bottom-right) - Anti-diagonal: Elements where
row + column == n-1(top-right to bottom-left)
Return the largest prime found on these diagonals, or 0 if no prime exists.
Remember: A prime number is greater than 1 and has exactly two divisors: 1 and itself.
Example: In matrix [[1,2,3],[5,6,7],[9,10,11]], the main diagonal is [1,6,11] and anti-diagonal is [3,6,9]. The largest prime among [1,6,11,3,9] is 11.
Input & Output
example_1.py โ Basic Matrix
$
Input:
nums = [[1,2,3],[5,6,7],[9,10,11]]
โบ
Output:
11
๐ก Note:
Main diagonal: [1,6,11], Anti-diagonal: [3,6,9]. All diagonal elements: {1,3,6,9,11}. Prime numbers: {3,11}. The largest prime is 11.
example_2.py โ No Prime Case
$
Input:
nums = [[1,2,3],[5,6,7],[9,10,12]]
โบ
Output:
0
๐ก Note:
Main diagonal: [1,6,12], Anti-diagonal: [3,6,9]. All diagonal elements: {1,3,6,9,12}. Prime numbers: {3}. The largest prime is 3.
example_3.py โ Single Element
$
Input:
nums = [[2]]
โบ
Output:
2
๐ก Note:
Only one element in the matrix which is on both diagonals. Since 2 is prime, the answer is 2.
Constraints
- 1 โค n โค 300 where n = nums.length = nums[i].length
- 1 โค nums[i][j] โค 4 ร 106
- Matrix is always square (n ร n)
Visualization
Tap to expand
Understanding the Visualization
1
Map the Paths
Identify the two diagonal paths: main (โ) and anti (โ) diagonals
2
Collect Treasures
Walk both paths simultaneously, collecting all unique treasures
3
Test for Prime Value
Examine each treasure to determine if it's a prime number
4
Find Maximum Prime
Select the most valuable (largest) prime treasure found
Key Takeaway
๐ฏ Key Insight: We only need to examine diagonal elements (at most 2n-1 unique values) rather than the entire nยฒ matrix, making this problem much more efficient than it initially appears.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code