Problem Description
Given a square matrix of integers, the task is to find and return the largest prime number that appears on either of the two diagonals of the matrix. If no prime exists on the diagonals, return 0.
Key Insights
- Only elements on the main diagonal (nums[i][i]) and the secondary diagonal (nums[i][n-i-1]) are considered.
- Use a set (or equivalent) to avoid duplicate diagonal elements especially for matrices with an odd dimension.
- A helper function is essential to check if a given number is prime.
- Iterate through the candidate numbers, check for prime property, and keep track of the maximum prime found.
Space and Time Complexity
Time Complexity: O(n * sqrt(m)), where n is the dimension of the matrix and m is the value of the number (up to 4*10^6) checked for primality. Space Complexity: O(n) for storing the set of diagonal numbers.
Solution
We first extract all unique elements from both diagonals of the matrix. A set is used to ensure that even if an element appears in both diagonals (like the center element in an odd-sized matrix), it is processed only once. Then for each element in the set, we use a helper function to check if it is prime. In the prime check, we verify that the number is greater than 1 and test for factors up to the square root of the number. Finally, the maximum prime found among the diagonal candidates is returned; if no prime number is found, we return 0.