#2614

Prime In Diagonal

Easy
ArrayMathMatrixNumber TheorySieve of Eratosthenes for prime checking.Matrix traversal techniques.
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can optimize the prime checking by using a sieve method to precompute all prime numbers up to the maximum possible value in the matrix, allowing for O(1) prime checks.

⚙️

Algorithm

5 steps
  1. 1Step 1: Use the Sieve of Eratosthenes to generate a list of prime numbers up to 4 * 10^6.
  2. 2Step 2: Initialize a variable to track the largest prime found.
  3. 3Step 3: Iterate through each index of the matrix to access both diagonals.
  4. 4Step 4: For each diagonal element, check if it is prime using the precomputed list. If it is and larger than the current largest prime, update the largest prime.
  5. 5Step 5: After checking all diagonal elements, return the largest prime found, or 0 if none were found.
solution.py25 lines
1# Full working Python code
2import math
3
4def sieve_of_eratosthenes(max_num):
5    is_prime = [True] * (max_num + 1)
6    is_prime[0] = is_prime[1] = False
7    for i in range(2, int(math.sqrt(max_num)) + 1):
8        if is_prime[i]:
9            for j in range(i * i, max_num + 1, i):
10                is_prime[j] = False
11    return is_prime
12
13def largest_prime_diagonal(nums):
14    max_val = 4 * 10**6
15    is_prime = sieve_of_eratosthenes(max_val)
16    largest_prime = 0
17    n = len(nums)
18    for i in range(n):
19        diag1 = nums[i][i]
20        diag2 = nums[i][n - i - 1]
21        if is_prime[diag1]:
22            largest_prime = max(largest_prime, diag1)
23        if is_prime[diag2]:
24            largest_prime = max(largest_prime, diag2)
25    return largest_prime if largest_prime > 0 else 0

Complexity note: The time complexity is O(n) for checking the diagonals after precomputing primes, and the space complexity is O(n) for storing the prime information.

  • 1Diagonal elements can be accessed using simple index calculations.
  • 2Precomputing prime numbers allows for efficient prime checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.