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: 3
💡 Note: Main diagonal: [1,6,15], Anti-diagonal: [3,6,9]. Prime numbers on diagonals: 3. Largest prime 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 INPUT 1 2 3 5 5 6 7 8 9 Main Diagonal (red) Anti-Diagonal (blue) Input Array: nums = [[1,2,3], [5,5,6], [7,8,9]] ALGORITHM STEPS 1 Get Diagonal Elements Main: nums[i][i] Anti: nums[i][n-i-1] 2 Extract Values Main: [1, 5, 9] Anti: [3, 5, 7] 3 Check Prime Status 1: Not prime (less than 2) 3, 5, 7: Prime numbers 9: Not prime (3x3) 4 Find Maximum Prime Primes found: {3, 5, 7} max(3, 5, 7) = 7 Prime Check Table: 1-No 3-OK 5-OK 7-OK 9-No FINAL RESULT 7 Largest Prime Output: 7 Explanation: 7 is found at position nums[2][0] on the anti-diagonal and is the largest prime found. Key Insight: Direct Diagonal Access (O(n) Time) Instead of iterating through the entire n x n matrix (O(n^2)), we directly access diagonal elements using: Main diagonal: nums[i][i] for i in [0, n-1] | Anti-diagonal: nums[i][n-1-i] for i in [0, n-1] This reduces time complexity from O(n^2) to O(n), checking only 2n elements (minus center overlap). TutorialsPoint - Prime In Diagonal | Optimized - Direct Diagonal Access Time: O(n * sqrt(max_val)) | Space: O(1)
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