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
161139Prime Treasure Analysis๐Ÿ” Collected: {1, 3, 6, 9, 11}โœจ Prime Check:โ€ข 1: Not prime (< 2)โ€ข 3: Prime โœ“โ€ข 6: Not prime (6 = 2ร—3)โ€ข 9: Not prime (9 = 3ร—3)โ€ข 11: Prime โœ“๐Ÿ† Largest Prime: 11
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.4K Views
Medium Frequency
~12 min Avg. Time
892 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