Prime In Diagonal — LeetCode 2614 Python Solution
EasyArrayMathMatrixNumber Theory
- Problem
- #2614
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [[1,2,3],[5,6,7],[9,10,11]]
- Output
- 11
- Explanation
- The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11.
Python solution
Python
class Solution:
def diagonalPrime(self, nums: List[List[int]]) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
n = len(nums)
ans = 0
for i, row in enumerate(nums):
if is_prime(row[i]):
ans = max(ans, row[i])
if is_prime(row[n - i - 1]):
ans = max(ans, row[n - i - 1])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \sqrt{M}), where n and M are the number of rows of the array and the maximum value in the array, respectively |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2614. Prime In Diagonal is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2614. Prime In Diagonal?
- LeetCode 2614. Prime In Diagonal is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2614. Prime In Diagonal?
- The Python solution on this page runs in O(n \times \sqrt{M}), where n and M are the number of rows of the array and the maximum value in the array, respectively.
- What is the space complexity of LeetCode 2614. Prime In Diagonal?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2614. Prime In Diagonal cover?
- LeetCode 2614. Prime In Diagonal is tagged Array, Math, Matrix and Number Theory on LeetCode.