Prime In Diagonal — Easy Problem & Solution
Return the largest prime that lies on either diagonal of the square matrix nums, or 0 if neither diagonal holds a prime.
- Difficulty: Easy
- Topics: Arrays, Math, Matrix, Number Theory
- Asked at: Amazon, Adobe, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Return the largest prime that lies on either diagonal of the square matrix nums, or 0 if neither diagonal holds a prime.
The diagonals are the cells with i == j and the cells with i + j == n - 1.
Example 1
Input: nums = [[1,2,3],[5,6,7],[9,10,11]]
Output: 11
Explanation: The diagonals hold 1, 6, 11, 3, 6, 9; the largest prime is 11.
Example 2
Input: nums = [[1,2,3],[5,17,7],[9,11,10]]
Output: 17
Example 3
Input: nums = [[1,4],[6,8]]
Output: 0
Explanation: No diagonal entry is prime.
Constraints
1 <= nums.length <= 300nums.length == nums[i].length1 <= nums[i][j] <= 4000000
How to solve Prime In Diagonal
Visit the 2n diagonal cells and keep the largest prime. Checking value > best before testing primality keeps the expensive part rare.
Approach
- For each row
i, look atnums[i][i]andnums[i][n-1-i]. - If a value exceeds the current best, test it for primality by trial division up to its square root.
- Return the best found, or 0.
Why it works
Trial division to sqrt(x) is enough because a composite x must have a factor at or below its square root. Writing the loop bound as d * d <= x avoids a floating-point square root entirely, which matters where the harness has no math library. The > best guard means most cells cost one comparison.
Complexity
- Time —
O(n · sqrt(V)) - Space —
O(1)
Pitfalls
- The two diagonals overlap at the centre of an odd-sized matrix — harmless here, since taking a maximum is idempotent.
- 1 is not prime, and the answer for 'no prime found' is 0.
- A sieve up to 4,000,000 also works but is far more memory than the
2ncells need.
Reference solution
Python
from typing import List
def diagonalPrime(nums: List[List[int]]) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
d = 2
while d * d <= x:
if x % d == 0:
return False
d += 1
return True
n = len(nums)
best = 0
for i in range(n):
for v in (nums[i][i], nums[i][n - 1 - i]):
if v > best and is_prime(v):
best = v
return bestJavaScript
var diagonalPrime = function(nums) {
var isPrime = function(x) {
if (x < 2) return false;
for (var d = 2; d * d <= x; d++) if (x % d === 0) return false;
return true;
};
var n = nums.length;
var best = 0;
for (var i = 0; i < n; i++) {
var a = nums[i][i], b = nums[i][n - 1 - i];
if (a > best && isPrime(a)) best = a;
if (b > best && isPrime(b)) best = b;
}
return best;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.